Hibernate Interview Questions and Answers
Ques 46. What is the difference between the session.get() method and the session.load() method?
Ans. Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(&) returns null.
Ques 47. What is the difference between the session.update() method and the session.lock() method?Ans. Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction.
Note: When you reattach detached objects you need to make sure that the dependent objects are reatched as well.
Ques 48. How would you reatach detached objects to a session when the same object has already been loaded into the session?Ans. You can use the session.merge() method call.
Ques 49. What are the general considerations or best practices for defining your Hibernate persistent classes?Ans. 1.You must have a default no-argument constructor for your persistent classes and there should be getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persistable instance variables.
2.You should implement the equals() and hashCode() methods based on your business key and it is important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when saving the object.
3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster.
4.The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects.
5.Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less verbose than *.hbm.xml files.
Ques 50. What does ORM consists of?Ans. An ORM solution consists of the followig four pieces:
* API for performing basic CRUD operations
* API to express queries refering to classes
* Facilities to specify metadata
* Optimization facilities : dirty checking,lazy associations fetching
Most helpful rated by users: