我使用Hibernate5.2,在没关闭session的情况下测试发现connection hashcode都是一样的
public void testSaveStudentsWithOpenSession() {
/*Hibernate5.x版本的测试方式*/
//获得服务注册对象
// 使用 final修饰引用变量时,当该引用变量被初始化赋值后,就不能再指向其他对象,但是该对象的内容可以修改。
// TODO 或许正是在这里使用了final,使用openSession而没有手动关闭,多次之后而【不会】导致连接池溢出
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
try {
//获得sessionFactory对象
SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
//获得session对象
Session session1 = sessionFactory.openSession(); //
//开启事务
Transaction transaction = session1.beginTransaction();
//生成一个学生对象
Students s = new Students(1,"张三丰","男",new Date(),"北京");
session1.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
// TODO Auto-generated method stub
System.out.println("connection hashcode:" + connection.hashCode());
}
});
session1.save(s);
//session1.close() //
transaction.commit(); //提交事务
//获取第二个session
Session session2 = sessionFactory.openSession();
Transaction transaction2 = session2.beginTransaction();
s = new Students(2,"sd丰","男",new Date(),"北京");
session2.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
// TODO Auto-generated method stub
System.out.println("connection hashcode:" + connection.hashCode());
}
});
session2.save(s);
//session1.close() //
transaction2.commit(); //提交事务
} catch (Exception e) {
e.printStackTrace();
StandardServiceRegistryBuilder.destroy( registry );
}
}
}