Hibernate 创建session的步骤

来源:互联网 发布:yum 强制卸载命令 编辑:程序博客网 时间:2024/04/30 03:56
//获取配置对象Configuration configuration = new Configuration().configure();//获取注册服务对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();//获取session工厂对象SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);//创建会话对象,需要手动关闭session//Session session = sessionFactory.openSession();//无需手动关闭session,这种会话对象在事物提交或者回滚后会自动关闭Session session = sessionFactory.getCurrentSession();//创建事物Transaction transaction = session.getTransaction();//开启事物transaction.begin();//先生成被控类对象,注意pid是18位IdCard card = new IdCard("123456789012345678","张无忌");//创建一个学生Student student =  new Student(card,"男",new Date(),"计算机");session.save(card);session.save(student);//使用openSession();创建session的话,最后需要手动关闭session,否则会一直持有connection的引用//session.close();//提交事物transaction.commit();

原创粉丝点击