May 05, 2017

#Part 2: Hibernate Interview Questions


What is the difference between save() , persist() ansaveOrUpdate methods of session object?
  • save() can only INSERT records but saveOrUpdate() can either INSERT or UPDATE records. 
  • session.save() saves the object and returns the id of the instance, whereas persist do not return anything after saving the instance. The return type of save() is a Serializable object, while return type of persist() method is void.
  • persist() method guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries. save() method does not guarantee the same, it returns an identifier, and if an INSERT has to be executed to get the identifier (like "identity" generator), this INSERT happens immediately, no matter if you are inside or outside of a transaction.
What is the difference between get() and load() methods of session object?
  • get() returns null if no data is present, whereas load throws ObjectNotFoundException exception in such case.
  • get() always hits the database, whereas load() method doesn't hit the database.
  • get() returns actual object, whereas load() return proxy without hitting the database unless required.

When do you use merge() and update() in Hibernate?
Use update() when you are sure that the Hibernate Session does not contain an already persistent instance with the same id. merge() helps in merging your modifications at any time without considering the state of the Session.

How can we reattach any detached objects in Hibernate?
Objects which have been detached and are no longer associated with any persistent entities can be reattached by calling session.merge() method of session class.

What’s the use of session.lock() in hibernate?
session.lock() method of session class is used to reattach an object which has been detached earlier. This method of reattaching doesn’t check for any data synchronization in database while reattaching the object and hence may lead to lack of synchronization in data.

Difference between save() and saveOrUpdate() method of Hibernate?
Both save() and saveOrUpdate() method are used to store an object into Database. save() can only Insert records but saveOrUpdate() can either Insert or Update records.

Difference between the transient, persistent and detached state in Hibernate?
  • Transient state: New objects are created in the Java program but are not associated with any Hibernate Session.
  • Persistent state: An object which is associated with a Hibernate session is called Persistent object. While an object which was earlier associated with Hibernate session but currently it’s not associate is known as a detached object. You can call save() or persist() method to store those object into the database and bring them into the Persistent state.
  • Detached state: You can re-attach a detached object to Hibernate sessions by calling either update() or saveOrUpdate() method.
Difference
  • When an entity is first created, it goes to transient state and this time it doesn't have a representation in database i.e. there will be no row corresponding to this object in Entity table. On the other hand, both Persistent and Detached objects have corresponding representation in database.
  • The transient and detached object are not associated with session, hibernate knows nothing about them, but Persistent object is associated with session. Therefore any changes in the Persistent object will reflect in database because Hibernate will automatically run update queries to save changes on Persistent object.
  • Both transient and detached objects are eligible for garbage collection because they are not associated with session, but persistent object is not eligible to garbage collection until session is open because Hibernate Session object keep a reference of Persistent object.
  • When an entity is first created in application using  the new() operator, it remains in transient state. It can move to Persistent state when you associate it with a session by calling Session.save() method. When you close() the session or evict() that object from session, it moves to detached state. You can again move a detached object to Persistent state by calling Session.update() or Session.saveOrUpdate() method.
  • FYI, if we detach the object and then call the commit(), the database will be updated with the latest details. Hence, always call detach() after the commit().
Difference between clear(), evict(), remove() and close() methods in Hibernate?
clear(): When session.clear() is called inside transaction boundary then all objects which are currently associate with particular session will be disconnected, cleaned or no longer associate with that session instance. Therefore, after calling this method nothing will be performed on persistence layer or DB. e.g:

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

House house = (House)session.get(House.class, 1);

house.setFulladdress("Rockefeller Plaza");
session.clear();
tx.commit();
session.close();

After calling session.clear(), house object is disconnected from the session object. i.e house object is moved from persistent to detached state. That's why the table is not updated when we change the full address of the house, even though the transaction is committed after it (house object is in non-transaction state).

close() closes the session, release the JDBC connection and clean up. It is not strictly necessary to close the session, but you must at least using disconnect it using session.disconnect().

evict()session.evict(obj) removes the object from the session. This method is used to dissociate or disconnect the specified object from the session. The entity has an associated identifier, but is no longer associated with a persistence context. e.g

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

House house1 = (House)session.get(House.class, 1);
House house2 = (House)session.get(House.class, 2);

house1.setFulladdress("Rockefeller Plaza");
house2.setFulladdress("Madison Square Garden");

session.evict(house1);

tx.commit();
session.close();

house1 data will not updated because it is evicted, but Full Address of house2 will be updated in database.

remove()session.remove(obj) the entity has an associated identifier and is associated with a persistence context, however it is scheduled for removal from the database.

What is lazy loading?
Lazy loading is a technique in which objects are loaded on demand basis. Since Hibernate 3, lazy loading is by default enabled so that child objects are not loaded when parent is loaded.

What is Named SQL Query?
Hibernate provides another important feature called Named Query using which you can define at a central location and use them anywhere in the code. We can create named queries for both HQL as well as for Native SQL. These Named Queries can be defined in Hibernate mapping files with the help of JPA annotations @NamedQuery and @NamedNativeQuery.

Which are the design patterns that are used in Hibernate framework?
  • Domain Model Pattern: An object model of the domain that incorporates both behavior as well as data.
  • Data Mapper: A layer of the map that moves data between objects and a database while keeping it independent of each other and the map itself.
  • Proxy Pattern: It is used for lazy loading.
  • Factory Pattern: Used in SessionFactory.
Name some of the important interfaces of Hibernate framework?
SessionFactory (org.hibernate.SessionFactory), Session (org.hibernate.Session) and Transaction (org.hibernate.Transaction).

What is Hibernate SessionFactory?
  • SessionFactory is an interface that is used to get the Session objects. 
  • The SessionFactory is a heavyweight object so usually, it is created during application startup and kept for later use. 
  • The SessionFactory is a thread safe object and used by all the threads of an application. 
  • We would need one SessionFactory object per database using a separate configuration file. If we are using multiple databases then we would have to create multiple SessionFactory objects.
The SessionFactory interface is available in the org.hibernate.sessionFactory and can be obtained by the Configuration object.
Configuration configuration = new Configuration().configure();
SessionFactory factory = configuration.buildSessionFactory(); 

Methods of SessionFactory interface
  • public void close() is used to destroy the current SessionFactory and releases all the resources (cache, connection pools). If the SessionFactory is already closed, no-operation will be performed.  
  • public Map getAllClassMetadata() is used to retrieve the ClassMetadata for all mapped entities. It will return a Map containing all ClassMetadata mapped by the corresponding String entityname.  
  • public Map getAllCollectionMetadata() is used to retrieve the CollectionMetadata for all mapped collections. It returns a Map from String to CollectionMetadata.  
  • public Cache getCache() can directly access the underlying cache regions.
  • public ClassMetadata getClassMetadata(Class entityClass) is used to retrieve the ClassMetadata associated with the given entity class. The Metadata will become null if there is no entity mapped with it.  
  • public CollectionMetadata getCollectionMetadata(String roleName) is used to retrieve the CollectionMetadata associated with the named collection role. If no such Collection is mapped with the Metadata, then it will become null.  
  • public Session getCurrentSession() is used to obtain the current Hibernate Session and associates the Session with the current Session.  
  • public Statistics getStatistics() is used to retrieve the statistics for this SessionFactory.  
  • public boolean isClosed() is used to check whether the SessionFactory is open or closed. It will return true if the factory is already closed else false.  
  • public Session openSession() is used to open a Session. The configured connection provider will provide the database connections when needed.  
  • public Session openSession(Connection connection) is used to open a Session using the specified database connection. When we supply a JDBC connection, then the second-level cache will be automatically disabled.  
  • public Session openSession(Interceptor interceptor) is used to open a Session, using the specified interceptor. An interceptor allows user code to intercept or change the property values. The configured connection provider will provide the database connections when needed.          
  • public StatelessSession openStatelessSession() is used to open a new stateless session using the specified database connection. A stateless Session has no persistent object associated with it. It does not implement a first-level cache and a second-level cache.
What is Session in Hibernate and how to get it?
  • Hibernate Session is the interface between Java application layer and Hibernate. It is available in the org.hibernate.session package.
  • A Session is used to get a physical connection with a database.
  • The Session object created is lightweight and designed to be instantiated each time an interaction is needed with the database. This Session provides methods to create, read, update and delete operations for a constant object. 
  • To get the Session, you can execute HQL queries, SQL native queries using the Session object.
  • The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed.

Is SessionFactory a thread-safe object?
Yes, SessionFactory is a thread-safe and can be accessed by multiple threads simultaneously.

Is Session a thread-safe object?
No, Session is not thread-safe.

What is the difference between openSession and getCurrentSession?
  • This getCurrentSession() method returns the session bound to the context and for this to work, we need to configure it in Hibernate configuration file. Since this session object belongs to the context of Hibernate, it is okay if we don’t close it. Once the SessionFactory is closed, this session object gets closed.
  • openSession() method helps in opening a new session. We should close this session object once you are done with all the database operations. And also, we should open a new session for each request in a multi-threaded environment.
Discuss the Collections in Hibernate. What are the collection types in Hibernate?
Hibernate provides the facility to persist the Collections. A Collection basically can be a List, Set, Map, Collection, Sorted Set, Sorted Map. java.util.List, java.util.Set, java.util.Collection, etc, are some of the real interface types to declared the persistent collection-value fields. Hibernate injects persistent Collections based on the type of interface. The collection instances generally behave like the types of value behavior.

There are five collection types in hibernate used for one-to-many relationship mappings. Bag, Set, List, Array, and Map.

What is a Hibernate Template class? What are the benefits of using Hibernate template?
When we integrate Spring and Hibernate, Spring ORM provides two helper classes : HibernateDaoSupport and HibernateTemplate. The main reason to use them was to get two things, the Session from Hibernate and Spring Transaction Management.

FYI, from Hibernate 3.0.1, we can use the SessionFactory getCurrentSession() method to get the current session.

The major advantage of using this Template class is the exception translation, but that can be achieved easily by using @Repository annotation with service classes.

Here are a few benefits of using this Hibernate template class:
  • Automated Session closing ability.
  • The interaction with the Hibernate Session is simplified.
  • Exception handling is automated.
What is Dirty Checking in Hibernate?
Dirty Checking feature permits the users to avoid time-consuming write actions. It changes or updates fields that need to be changed or updated, while keeping the remaining fields untouched and unchanged.

What is the difference between Hibernate's @NotNull vs @Column(nullable = false)?
When used on the JPA entity, both of them essentially prevent storing null values in the underlying database, there are significant differences between these two approaches.

The @NotNull annotation is part of the BeanValidation specification. You need to add a dependency to the Hibernate Validator project. The @Column annotation is part of the JPA specification, and you already use all required dependencies.So no need to add any extra dependency in your project.

The @NotNull annotation triggers a validation by the BeanValidation implementation when a pre-update or a pre-persist lifecycle event gets triggered. So, the validation happens within your Java application.

Hibernate doesn’t perform any validation if you annotate an attribute with @Column(nullable = false). This annotation only adds a not null constraint to the database column, if Hibernate creates the database table definition. The database then checks the constraint, when you insert or update a record.

The @Column(nullable = false) annotation has no effect if Hibernate doesn’t generate the table definition. That means that you need to pay extra attention to your database script if you create your database schema with Flyway or Liquibase.

You should always use the @NotNull annotation, which is defined by the Bean Validation specification. It configures a validation step that gets performed before Hibernate executes the SQL statement.

-K Himaanshu Shuklaa..

No comments:

Post a Comment