Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

java - Spring + Hibernate session lifecycle

How properly "lifecycle" of a Hibernate session under Spring should be done?

The SessionFactory is created automatically by Spring and is taking its DB connections from Glassfish connection pool. At the moment I am getting a Hibernate session via SessionFactory.getCurrentSession(). Then I start transaction, do the work and then commit() or rollback() at the end. Do I need to do any other actions like disconnect(), close(), flush() or any others at any time so connections would be properly returned back to the pool or is everything already automatically done by Spring?

With plenty of these methods it is a little confusing for me at the moment to understand when what should be done, maybe someone can point to right direction?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As SessionFactory is created automatically by Spring, Spring framework will take care of closing the connection. Check out Spring Resource Management

If you want to check. You can check the log, if you are using logging for your app. It'll be like :

(main) INFO [AnnotationSessionFactoryBean] Closing Hibernate SessionFactory

I get following lines from this link

The main contract here is the creation of Session instances. Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory. The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping. Implementors must be threadsafe.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...