跳至主要內容

[java] Different ways to get the Connection object using Hibernate

1) session.connection() – this method is deprecated. it is not available on Hibernate4.
2) session.doWork() – this method doesn’t return Connection object, but inside what ever operation we want to do using connection object we can do.
3) session.doReturningWork() – this method returns dynamic type value. In the below example i am return Connection object.
4) SessionImpl.connection() – Down casting the Session object to SessionImpl. By using SessionImpl we will get the Connection object.
5) ConnectionProvider.getConnection() – Using ConnectionProvider getConnection() method.
Full Example:
package com.varasofttech.client;
import java.sql.Connection;
import java.sql.SQLException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.SessionImpl;
import org.hibernate.jdbc.ReturningWork;
import org.hibernate.jdbc.Work;
import com.varasofttech.util.HibernateUtil;
public class Application {
public static void main(String[] args) {
// Different ways to get the Connection object using Session
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
// Way1 – using doWork method
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
// do your work using connection
}
});
// Way2 – using doReturningWork method
Connection connection = session.doReturningWork(new ReturningWork() {
@Override
public Connection execute(Connection conn) throws SQLException {
return conn;
}
});
// Way3 – using Session Impl
SessionImpl sessionImpl = (SessionImpl) session;
connection = sessionImpl.connection();
// do your work using connection
// Way4 – using connection provider
SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) session.getSessionFactory();
ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider();
try {
connection = connectionProvider.getConnection();
// do your work using connection
} catch (SQLException e) {
e.printStackTrace();
}
}
}
reference: http://myjourneyonjava.blogspot.tw/2014/12/different-ways-to-get-connection-object.html

分類:java
由 Compete Themes 設計的 Author 佈景主題