Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SessionFactory.openSession(Connection) in Hibernate 4

Tags:

java

hibernate

I am pumping existing JDBC connection using SessionFactory.openSession(Connection). Now in 4.0 this method is not available. Which method should I use for this?

like image 267
Dragon Avatar asked May 24 '12 04:05

Dragon


People also ask

What is a SessionFactory () in Hibernate?

Most importantly, the SessionFactory in Hibernate is responsible for the creation of Session objects. The Hibernate Session provides methods such as save, delete and update, all of which are used to perform CRUD-based operations on the database to which the SessionFactory connects.

Can we have multiple SessionFactory in Hibernate?

Session factory is long live multithreaded object. Usually one session factory should be created for one database. When you have multiple databases in your application you should create multiple SessionFactory object. Configuration cfg=new Configuration();

What is difference between getCurrentSession () and openSession () in Hibernate?

openSession() always opens a new session that you have to close once you are done with the operations. SessionFactory. getCurrentSession() returns a session bound to a context - you don't need to close this.

Is SessionFactory Singleton in Hibernate?

@DarkHorse SessionFactory is not Singleton , it is used as singleton , it is immutable docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/…


1 Answers

You can use SessionFactory.withOptions() and SessionBuilder.connection(Connection connection).

SessionBuilder connection(Connection connection)

Adds a specific connection to the session options

Parameters: connection - The connection to use.

Returns: this, for method chaining

Example:

SessionBuilder sb = SessionFactory.withOptions();
Session session = sb.connection(connection).openSession();
like image 185
Pau Kiat Wee Avatar answered Oct 05 '22 19:10

Pau Kiat Wee