Tuesday, May 7, 2013

Interview Question on Hibernate Framework



Hibernate Interview Questions and Answers for Java J2EE DevelopersHere is my list of Hibernate interview question, which I have collected from friends and colleagues. Hibernate is a popular Object Relational Mapping framework and good knowledge of advantages offered by Hibernate along with Hibernate Session API is key to do well in any Hibernate Interview.

Difference between get and load in Hibernate?
get vs load is one of the most frequently asked Hibernate Interview question, since correct understanding of both get() and load() is require to effectively using Hibernate. Main difference between get and load is that, get will hit the database if object is not found in the cache and returned completely initialized object, which may involve several database call while load() method can return proxy, if object is not found in cache and only hit database if any method other than getId() is called. This can save lot of performance in some cases. You can also see difference between get and load in Hibernate for more differences and detailed discussion on this question.


Difference between save, persist and saveOrUpdate methods in Hibernate?
After get vs load, this is another Hibernate Interview question which appears quite often. All three methods i.e. save()saveOrUpdate() and persist() is used to save objects into database, but has subtle differences e.g. save() can only INSERT records but saveOrUpdate() can eitheINSERT or UPDATE records. Also, return type of save() is a Serializable object, while return type of persist() method is void. You can also check save vs persist vs saveOrUpdate for complete differences between them in hibernate.


What is named SQL query in Hibernate?
This Hibernate Interview question is related to query functionality provided by Hibernate. Named queries are SQL queries which are defined in mapping document using <sql-query> tag and called using Session.getNamedQuery() method. Named query allows you to refer a particular query by the name you provided, by the way you can define named query in hibernate either by using annotations or xml mapping file, as I said above. @NameQuery is used to define single named query and @NameQueries is used to define multiple named query in hibernate.


What is SessionFactory in Hibernate? is SessionFactory thread-safe?
Another common Interview questions related to Hibernate framework. SessionFactory as name suggest is a factory to create hibernate Session objects. SessionFactory is often built during start-up and used by application code to get session object. It acts as single data store and its also thread-safe so that multiple thread can use same SessionFactory. Usually a Java JEE application has just one SessionFactory, and individual threads, which are servicing client’s request obtain hibernate Session instances from this factory, that’s why any implementation of SessionFactory interface must be thread-safe. Also internal state of SessionFactory, which contains all meta data about Object/Relational mapping iImmutable and can not be changed once created.


What is Session in Hibernate? Can we share single Session among multiple threads in Hibernate?
This is usually asked as follow-up question of previous Hibernate Interview question. After SessionFactory its time for SessionSession represent a small unit of work in Hibernate, they maintain connection with database and they are not thread-safe, it means you can not share Hibernate Session between multiple threads. Though Session obtains database connection lazily it's good to close session as soon as you are done with it.


What is difference between sorted and ordered collection in hibernate?
This is one of the easy Hibernate interview question you ever face. A sorted collection is sorted in memory by using Java Comparator, while a ordered collection uses database's order by clause for ordering. For large data set it's better to use ordered collection to avoid anOutOfMemoryError in Java, by trying to sort them in memory.


What is difference between transient, persistent and detached object in Hibernate?
In Hibernate, Object can remain in three state transientpersistent or detached.  An object which is associated with Hibernate session is called persistent object. Any change in this object will reflect in database based upon your flush strategy i.e. automatic flush whenever any property of object change or explicit flushing by calling Session.flush() method. On the other hand if an object which is earlier associated with Session, but currently not associated with it are called detached object. You can reattach detached object to any other session by calling either update() or saveOrUpdate() method on that session. Transient objects are newly created instance of persistence class, which is never associated with any Hibernate Session. Similarly you can call persist() or save() methods to make transient object persistent. Just remember, here transient doesn’t represent transient keyword in Javawhich is altogether different thing.

What does Session lock() method do in Hibernate?
This one is one of the tricky Hibernate Interview question, because Session's lock() method reattach object without synchronizing or updating with database. So you need to be very careful while using lock() method. By the way you can always use Session's update() method to sync with database during reattachment. Some time this Hibernate question is also asked as what is difference between Session's lock() and update() method. You can use this key point to answer that question as well.

What is Second level Cache in Hibernate?
This is one of the first interview question related to caching in Hibernate, you can expect few more. Second level Cache is maintained at SessionFactory level and can improve performance by saving fedatabase round trip. Another worth noting point is that second level cache is available to whole application rather than any particular session.

What is query cache in Hibernate ?
This question, Some times asked as a follow-up of last Hibernate Interview question, QueryCache actually stores result of sql query for future calls. Query cache can be used along with second level cache for improved performance. Hibernate support various open source caching solution to implement Query cache e.g. EhCache.

That's all on this list of Hibernate Interview questions and answer for Java developers. No one can doubt popularity of Hibernate as ORM solution and if you are going for a Java J2EE position, you can expect questions from Hibernate. Especially Spring and Hibernate are two most popular Java framework in JEE space. Don't forget to share any other Hibernate Interview Question, which you have been asked and good enough to share with Java community.

Comparator vs Comparable in Java



1) Comparator in Java is defined in java.util package while Comparable interface in Java is defined in java.lang package, which very much says that Comparator should be used as an utility to sort objects which Comparable should be provided by default.

2) Comparator interface in Java has method public int compare (Object o1, Object o2) which returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. While Comparable interface has method public int compareTo(Object o) which returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

3) If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified

4) Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implements Comparable interface.Its always good practice to override compareTo() for value objects.

5) If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using  Collections.sort() or Arrays.sort() method and object will be sorted based on there natural order defined by CompareTo method.

6)Objects which implement Comparable in Java  can be used as keys in a SortedMap like TreeMap or elements in a SortedSet  for example TreeSet, without specifying any Comparator.



Vector vs ArrayList in Java


Vector vs ArrayList in Java

Now let's see some key difference between Vector and ArrayList in Javathis will decide when is the right time to use Vector over ArrayList and vice-versa. Differences are based upon properties like synchronization, thread safety, speed, performance , navigation and Iteration over List etc.

1) Synchronization and thread-safety

First and foremost difference between Vector and ArrayList is that Vector is synchronized and ArrayList is not, what it means is that all the method which structurally modifies Vector e.g. add () or remove () are synchronized which makes it thread-safe and allows it to be used safely in a multi-threaded and concurrent environment. On the other hand ArrayList methods are not synchronized thus not suitable for use in multi-threaded environment. 

2) Speed and Performance

ArrayList is way faster than VectorSince Vector is synchronized and thread-safe it pays price of synchronization which makes it little slow. On the other hand ArrayList is not synchronized and fast which makes it obvious choice in a single-threaded access environment. 

3) Capacity

Whenever Vector crossed the threshold specified it increases itself by value specified in capacityIncrement field while you can increase size of ArrayList by calling ensureCapacity () method.

4) Enumeration and Iterator

Vector can return enumeration of items it hold by calling elements () method which is not fail-fast as opposed to Iterator and ListIterator returned by ArrayList.

5) Legacy

Another point worth to remember is Vector is one of those classes which comes with JDK 1.0 and initially not part of Collection framework but in later version it's been re-factored to  implement List interface so that it could become part of collection framework

Difference between SendRedirect() and Forward() in JSP Servlet


SendRedirect ():  

This method is declared in HttpServletResponse Interface.

Singanature: void sendRedirect(String url)

difference between sendRedirect and forward in jsp servletThis method is used to redirect client request to some other location for further processing ,the new location is available on different server or different context.our web container handle this and transfer the request using  browser ,and this request is visible in browser as a new request. Some time this is also called as client side redirect.


Forward():
This method is declared in RequestDispatcher Interface.
Signature: forward(ServletRequest request, ServletResponse response)

This method is used to pass the request to another resource for futher processing within the same server, another resource could be any servlet, jsp page any kind of file.This process is taken care by web container when we call forward method request is sent to another resource without the client being informed, which resource will handle the request it has been mention on requestDispatcher object which we can get by two ways either using ServletContext or Request. This is also called server side redirect.


RequestDispatcher rd = request.getRequestDispatcher("pathToResource");
  rd.forward(request, response);

Or

RequestDispatcher rd = servletContext.getRequestDispatcher("/pathToResource");
  rd.forward(request, response);

Difference between SendRedirect and Forward


Now let’s see some difference between these two method of servlet API in tabular format.

Forward()
SendRediret()
When we use forward method request istransfer to other resource within the sameserver for further processing.
In case of sendRedirect request is transfer to another resource to different domain or different server for futher processing.

In case of forward Web container handle all process internally and client or browser is not involved.

When you use SendRedirect containertransfers the request to client or browser so url given inside the sendRedirect method is visible as a new request to the client.

When forward is called on requestdispatherobject we pass request and response object so our old request object is present on new resource which is going to process our request

In case of SendRedirect call old request and response object is lost because it’s treated as new request by the browser.
Visually we are not able to see the forwarded address, its is transparent
In address bar we are able to see the new redirected address it’s not transparent.

Using forward () method is faster then send redirect.
SendRedirect is slower because one extra round trip is required beasue completely new request is created and old request object is lost.Two browser request requird.

When we redirect using forward and we want to use same data in new resource we can use request.setAttribute () as we have request object available.
But in sendRedirect if we want to use we have to store the data in session or pass along with the URL.

Serialization in Java

Serialization is the process of converting a set of object instance that contain refenece to each other into a linear stream of bytes which can be sent through a soket  store in a file or simply manipulated as a stream of data 

Object Serialization in Java is a process used to convert Object into a binary format which can be persisted into disk or sent over network to any other running Java virtual machine. Java provides Serialization API for serializing and deserializing object which includes java.io.Serializable, java.io.Externalizable, ObjectInputStream and ObjectOutputStream etc.

Serializable is a marker interfaces that tells the JVM is can write out the state of the object to some stream (basically read all the members, and write out their state to a stream, or to disk or something). The default mechanism is a binary format. You can also use it to clone things, or keep state between invocations, send objects across the network etc

Difference between Wait and Sleep in Java


Difference between Wait and Sleep in Java

  • Main difference between wait and sleep is that wait() method release the acquired monitor when thread is waiting while Thread.sleep() method keeps the lock or monitor even if thread is waiting.
  •   wait method in java should be called from synchronized method or block while there is no such requirement for sleep() method. Another difference is Thread.sleep() method is a static method and applies on current thread, while wait() is an instance specific method and only got wake up if some other thread calls notify method on same object. 
  • in case of sleep, sleeping thread immediately goes to Runnable state after waking up while in case of wait, waiting thread first acquires the lock and then goes into Runnable state. So based upon your need if you require a specified second of pause use sleep() method or if you want to implement inter-thread communication use wait method.
  • waiting thread can be awake by calling notify and notifyAll while sleeping thread can not be awaken by calling notify method.