Interview :: Hibernate
The HQL query is created with the help of the following syntax:
Session.createQuery
A criterion is added to a SQL query by using the Session.createCriteria.
Define persistent classes?
Classes whose objects are stored in a database table are called as persistent classes.
What is SessionFactory?
SessionFactory provides the instance of Session. It is a factory of Session. It holds the data of second level cache that is not enabled by default.
Yes, SessionFactory is a thread-safe object, many threads cannot access it simultaneously.
What is Session?
It maintains a connection between the hibernate application and database.
It provides methods to store, update, delete or fetch data from the database such as persist(), update(), delete(), load(), get() etc.
It is a factory of Query, Criteria and Transaction i.e. it provides factory methods to return these instances.
No, Session is not a thread-safe object, many threads can access it simultaneously. In other words, you can share it between threads.
No. | save() | persist() |
---|---|---|
1) | returns the identifier (Serializable) of the instance. | Return nothing because its return type is void. |
2) | Syn: public Serializable save(Object o) | Syn: public void persist(Object o) |
The differences between get() and load() methods are given below.
No. | get() | load() |
---|---|---|
1) | Returns null if an object is not found. | Throws ObjectNotFoundException if an object is not found. |
2) | get() method always hit the database. | load() method doesn't hit the database. |
3) | It returns the real object, not the proxy. | It returns proxy object. |
4) | It should be used if you are not sure about the existence of instance. | It should be used if you are sure that instance exists. |
The differences between update() and merge() methods are given below.
No. | The update() method | merge() method |
---|---|---|
1) | Update means to edit something. | Merge means to combine something. |
2) | update() should be used if the session doesn't contain an already persistent state with the same id. It means an update should be used inside the session only. After closing the session, it will throw the error. | merge() should be used if you don't know the state of the session, means you want to make the modification at any time. |
Let's try to understand the difference by the example given below:
After closing session1, e1 is in detached state. It will not be in the session1 cache. So if you call update() method, it will throw an error.
Then, we opened another session and loaded the same Employee instance. If we call merge in session2, changes of e1 will be merged in e2.