hibernate笔记一
1、在hibernate.cfg.xml中如果配置<property name="current_session_context_class">thread</property>,可以写
Configuration conf = new Configuration() //下面方法默认加载hibernate.cfg.xml文件 .configure(); //以Configuration创建SessionFactory //SessionFactory sf = conf.buildSessionFactory();//该方法过期 ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry(); SessionFactory sf = conf.buildSessionFactory(sr); //返回“当前的”工作单元 Session sess = sf.getCurrentSession(); //开始事务 Transaction tx = sess.beginTransaction(); //创建员工实例 Personal p = new Personal(); //设置员工属性 p.setName("LocoRocooo"); p.setFcode("gz2015"); //保存消息 sess.save(p); //提交事务 tx.commit(); //不需要关闭Session,直接关闭SessionFactory即可 //sess.close(); sf.close();
2、如果没有配置<property name="current_session_context_class">thread</property>,用Session sess = sf.getCurrentSession()会报错,提示没有配置:“No CurrentSessionContext configured!”,:
Configuration conf = new Configuration() //下面方法默认加载hibernate.cfg.xml文件 .configure(); //以Configuration创建SessionFactory //SessionFactory sf = conf.buildSessionFactory();//该方法过期 ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry(); SessionFactory sf = conf.buildSessionFactory(sr); //创建Session Session sess = sf.openSession(); //开始事务 Transaction tx = sess.beginTransaction(); //创建员工实例 Personal p = new Personal(); //设置员工属性 p.setName("LocoRocooo"); p.setFcode("gz2015"); //保存消息 sess.save(p); //提交事务 tx.commit(); //关闭Session sess.close(); sf.close();
如果用了Session sess = sf.openSession()则sess一定要关闭。
记录下来,以后再琢磨是什么原理。