标签:重复 action void alt utils 对象 nsa nfa ima
因为hibernate的代码大部分都是固定的,为了将减少重复的代码的书写,可以将这些代码封装为一个工具类,获取hibernate的session对象。
1、工具类:
package pers.zhb.HibernateUtils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtils { public static SessionFactory sessionFactory; static {//只执行一次,确保sessionFactory只创建一次,加载类的时候为静态变量分配一次内存 Configuration configuration = new Configuration().configure(); sessionFactory = configuration.buildSessionFactory(); } public static Session openSession(){//获得session Session session=sessionFactory.openSession(); return session; } public static Session getCurrentSession(){//获得与线程绑定的Session Session session=sessionFactory.getCurrentSession(); return session; } }
2、测试类(查询学号为937221509的学生信息):
import org.hibernate.Session; import org.hibernate.Transaction; import pers.zhb.domain.Student; import pers.zhb.HibernateUtils.HibernateUtils; public class HiberateSel { public static void testSel() { Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); Student student=session.get(Student.class,937221509); System.out.println(student); transaction.commit(); session.close(); } public static void main(String []args){ HiberateSel hinernateSel=new HiberateSel(); hinernateSel.testSel(); } }
标签:重复 action void alt utils 对象 nsa nfa ima
原文地址:https://www.cnblogs.com/zhai1997/p/11802658.html