Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly use clear(), evict() and close() methods in Hibernate?

Tags:

java

hibernate

I have read more information about these commands but didn't understand exactly what a right way to use these commands?.

I want to discover deeply the difference between clear(), evict() and close() methods in details. As I know evict() will clear particular object from session in hibernate and clear() will clear all objects from session.

How to use them correctly? Thanks

like image 405
Deepak Malav Avatar asked Nov 06 '17 17:11

Deepak Malav


People also ask

What is difference between evict and clear in hibernate?

As I know evict() will clear particular object from session in hibernate and clear() will clear all objects from session.

What does session evict () method do in hibernate?

The Session. evict() is used to remove a particular object from the cache associated with the session. Clearly, the evict() method removed the student object from the cache so that it was fetched again from the database.

How do you close a session in hibernate?

After each operation, closeSession() will close the session and set the threadLocal object to null.

Why do we need evict in hibernate?

In our hibernate development, sometimes we need to detach the session object because we need to change it and it may take time while changing. An easy example is if we are waiting for user input, in this case it is better to detach object from hibernate session, we do it by evict() method.


1 Answers

Approximately the definition of the commands:

Clear (): When this method get called inside transaction boundry then all objects which are currently associate with particular session will be disconnected / clean or no longer associate with that Session instance. Therefore, after calling this method nothing will be performed on persistance layer or DB.

Evict(): Removes the object from the session. This method is used to dissociate/disconnect the specified object from the session.

Close() : Close session by calling session.close() method, means End the session and releasing the JDBC Connection and clean up.

Examples of using these commands you can find here.

like image 156
Vasyl Lyashkevych Avatar answered Oct 25 '22 00:10

Vasyl Lyashkevych