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 );
}
}
}
在 hibernate 5.0 以上,如果注释掉 session.beginTransaction() 代码,那么 connection 的 hashCode 是不相等的;或者直接打印
System.out.println(session1 == session2); System.out.println(session1.hashCode() + " " + session2.hashCode());
老师用的是4.X版本,大版本更新有区别的
的确是一样的,我也试过了,老师讲的还是以参考为主吧,注重养成习惯,随手关闭,just like 出门要把门窗锁好
hibernate 版本换成4.2.21
更换以下代码:
//创建配置对象
Configuration cfg = new Configuration().configure();
//创建服务注册对象
final ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(
cfg.getProperties()).buildServiceRegistry();
//创建会话工厂对象
sessionFactory = cfg.buildSessionFactory(registry);
//创建会话对象
session = sessionFactory.openSession();