Is it good to close and open hibernate sessions?

I am developing an application that requires the state of objects to be read from the database at frequent intervals or triggers. However, once hibernate reads the state, it doesn't re-read it unless I explicitly close the session and don't read the object in the new session.

Is it a good idea to open a session every time I want to read an object and then close it afterwards? How much overhead is imposed on the application and database (we also use the c3p0 connection pool)?

Would it be enough to simply eject the entity from the session before re-reading it?

+2


a source to share


3 answers


You can also use refresh

to reload an object. Or evict

and clear

as @Bozho mentioned.

With connection pooling, the overhead of opening and closing a session is low. It takes a while to create a factory session.

The problem with closing and reopening the session is that the already loaded object will still be detached, if I remember well. This can be problematic for wrt for lazy loading. Therefore, it is better to keep the session open and use evict

, clear

or refresh

.

Please note that if you cross out the entity and access one of the already loaded objects, you will still get the old data.

MyEntity e = session.load( ... );
...
session.evict(e);         // remove entity from the cache
String p = e.myProperty;  // still the value at the time it was loaded
e = sesssion.load( ... ); // latest value

      



In your case, it might be better to introduce a design guide that says that any time an object is manipulated, it must be updated first.

MyEntity e = session.load( ... );
...
session.refresh( e );     // refresh entity and cache
String p = e.myProperty;  // latest value
e = sesssion.load( ... ); // latest value

      

The code above is just pseudocode, I haven't tested it.

Please note that if the session is open for a certain amount of time, the cache may grow, in which case you may need to clear

. Generally speaking, however, it is best to keep the session short to prevent this cache growth problem, plus connection timeout, transaction timeout and lock contention issues.

+3


a source


Yes. evict()

an object. If you want to clear the entire session, clear()

it.



The new session must be associated with either a request (stream) or a longer session.

0


a source


For columns that reference other tables, if you set the fetchtype to LAZY Hibernate, it will not load that data until it is explicitly requested. This saves a lot of time.

Column in Table

can be marked:

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="other_table_id", nullable = false)
private OtherTable otherTable;

      

So, until you do something like Table.getOtherTable().getValue()

load OtherTable

into session. So if you don't do something like that, you also don't need to evict him.

Note that this is pseudo-coding and may look slightly different for your program.

0


a source







All Articles