解决方案:
1.使用hibernate提供的解决方案在hibernate API中提到了替代方法
使用方法如下:
session.doWork(new Work() {
@Override
public void execute(Connection conn) throws SQLException {
doSomeThingWithJdbc(conn);
}
}
@Test
public void testConnection() {
org.hibernate.Session session = HibernateSessionFactory.getSession();
final List<String> list = new ArrayList<String>();
session.doWork(new Work() {
@Override
public void execute(Connection conn) throws SQLException {
// TODO Auto-generated method stub
String sql = "select name from xwtype where id=?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, 1);
ResultSet rs = stmt.executeQuery();
rs.next();
list.add(rs.getString("name"));
conn.close();
}
});
for (String s : list) {
System.out.println(s);
}
}
2.或者使用
SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection()
来自类org.springframework.orm.hibernate4.SessionFactoryUtils