What is SessionFactory in Hibernate? is SessionFactory thread-safe?
SessionFactory 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 is Immutable and can not be changed once created.
What is Session in Hibernate? Can we share single Session among multiple threads in Hibernate?
Session 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?
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 any OutOfMemoryError 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 transient, persistent 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.
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.
Difference between get and load method
http://javarevisited.blogspot.com/2012/07/hibernate-get-and-load-difference-interview-question.html
1. Behavior when Object is not found in Session Cache
get method of Hibernate Session class returns null if object is not found in cache as well as on database while load() method throws ObjectNotFoundException if object is not found on cache as well as on database but never return null.
Database hit
Get method always hit database while load() method may not always hit the database, depending upon which method is called.
Proxy
Get method never returns a proxy, it either returns null or fully initialized Object, while load() method may return proxy, which is the object with ID but without initializing other properties, which is lazily initialized. If you are just using returned object for creating relationship and only need Id then load() is the way to go.
Performance
get method will return a completely initialized object if Object is not on the cache but exists on Database, which may involve multiple round-trips to database based upon object relational mappings
while load() method of Hibernate can return a proxy which can be initialized on demand (lazy initialization) when a non identifier method is accessed. Due to above reason use of load method will result in slightly better performance, but there is a caveat that proxy object will throw ObjectNotFoundException later if corresponding row doesn’t exists in database, instead of failing immediately so not a fail fast behavior.
5. load method exists prior to get method which is added on user request.
When to use Session get() and load() in Hibernate
1. Use get method to determine if an instance exists or not because it can return null if instance doesn’t exists in cache and database and use load method to retrieve instance only if you think that instance should exists and non availability is an error condition.
2. consider using load method if your code doesn't access any method other than identifier or you are OK with lazy initialization of object, if persistent object is not in Session Cache because load() can return proxy.
Difference between save and saveOrUpdate in Hibernate
Difference between save vs persist and saveOrUpdate in Hibernate
save() generates a new identifier and INSERT record into database while saveOrUpdate can either INSERT or UPDATE based upon existence of record.
Clearly saveOrUpdate is more flexible in terms of use but it involves an extra processing to find out whether record already exists in table or not.
In summary save() method saves records into database by INSERT SQL query, Generates a new identifier and return the Serializable identifier back. On the other hand saveOrUpdate() method either INSERT or UPDATE based upon existence of object in database. If persistence object already exists in database then UPDATE SQL will execute and if there is no corresponding object in database than INSERT will run.
Difference between save and persist method in Hibernate
1. The return type: Similar to save method persist also INSERT records into database but return type of persist is void while return type of save is Serializable object.
2. both methods make a transient instance persistent. However, persist() method doesn't guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time.
3. 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 (e.g. "identity" generator), this INSERT happens immediately, no matter if you are inside or outside of a transaction.
4. Because of its above behavior of persist method outside transaction boundary, its useful in long-running conversations with an extended Session context. On the other hand save method is not good in a long-running conversation with an extended Session context.
What is named SQL query in 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 does Session lock() method do in Hibernate?
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.
What is Second level Cache in Hibernate?
Second level Cache is maintained at SessionFactory level and can improve performance by saving few database 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 ?
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.
Can we make an Hibernate Entity Class final?
Yes, you can make an Hibernate Entity class final, but that's not a good practice. Since Hibernate uses proxy pattern for performance improvement in case of lazy association, by making an entity final, Hibernate will no longer be able to use proxy, because Java doesn't allow extension of final class, thus limiting your performance improvement options. Though, you can avoid this penalty, if your persistent class is an implementation of interface, which declares all public methods defined in Entity class.
Read full article from 10 Hibernate Interview Questions and Answers for Java J2EE Programmers
SessionFactory 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 is Immutable and can not be changed once created.
What is Session in Hibernate? Can we share single Session among multiple threads in Hibernate?
Session 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?
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 any OutOfMemoryError 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 transient, persistent 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.
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.
Difference between get and load method
http://javarevisited.blogspot.com/2012/07/hibernate-get-and-load-difference-interview-question.html
1. Behavior when Object is not found in Session Cache
get method of Hibernate Session class returns null if object is not found in cache as well as on database while load() method throws ObjectNotFoundException if object is not found on cache as well as on database but never return null.
Database hit
Get method always hit database while load() method may not always hit the database, depending upon which method is called.
Proxy
Get method never returns a proxy, it either returns null or fully initialized Object, while load() method may return proxy, which is the object with ID but without initializing other properties, which is lazily initialized. If you are just using returned object for creating relationship and only need Id then load() is the way to go.
Performance
get method will return a completely initialized object if Object is not on the cache but exists on Database, which may involve multiple round-trips to database based upon object relational mappings
while load() method of Hibernate can return a proxy which can be initialized on demand (lazy initialization) when a non identifier method is accessed. Due to above reason use of load method will result in slightly better performance, but there is a caveat that proxy object will throw ObjectNotFoundException later if corresponding row doesn’t exists in database, instead of failing immediately so not a fail fast behavior.
5. load method exists prior to get method which is added on user request.
When to use Session get() and load() in Hibernate
1. Use get method to determine if an instance exists or not because it can return null if instance doesn’t exists in cache and database and use load method to retrieve instance only if you think that instance should exists and non availability is an error condition.
2. consider using load method if your code doesn't access any method other than identifier or you are OK with lazy initialization of object, if persistent object is not in Session Cache because load() can return proxy.
Difference between save and saveOrUpdate in Hibernate
Difference between save vs persist and saveOrUpdate in Hibernate
save() generates a new identifier and INSERT record into database while saveOrUpdate can either INSERT or UPDATE based upon existence of record.
Clearly saveOrUpdate is more flexible in terms of use but it involves an extra processing to find out whether record already exists in table or not.
In summary save() method saves records into database by INSERT SQL query, Generates a new identifier and return the Serializable identifier back. On the other hand saveOrUpdate() method either INSERT or UPDATE based upon existence of object in database. If persistence object already exists in database then UPDATE SQL will execute and if there is no corresponding object in database than INSERT will run.
Difference between save and persist method in Hibernate
1. The return type: Similar to save method persist also INSERT records into database but return type of persist is void while return type of save is Serializable object.
2. both methods make a transient instance persistent. However, persist() method doesn't guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time.
3. 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 (e.g. "identity" generator), this INSERT happens immediately, no matter if you are inside or outside of a transaction.
4. Because of its above behavior of persist method outside transaction boundary, its useful in long-running conversations with an extended Session context. On the other hand save method is not good in a long-running conversation with an extended Session context.
What is named SQL query in 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 does Session lock() method do in Hibernate?
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.
What is Second level Cache in Hibernate?
Second level Cache is maintained at SessionFactory level and can improve performance by saving few database 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 ?
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.
Can we make an Hibernate Entity Class final?
Yes, you can make an Hibernate Entity class final, but that's not a good practice. Since Hibernate uses proxy pattern for performance improvement in case of lazy association, by making an entity final, Hibernate will no longer be able to use proxy, because Java doesn't allow extension of final class, thus limiting your performance improvement options. Though, you can avoid this penalty, if your persistent class is an implementation of interface, which declares all public methods defined in Entity class.
Read full article from 10 Hibernate Interview Questions and Answers for Java J2EE Programmers
No comments:
Post a Comment