hibernate基本配置优化
前面已经说过hibernate的基本配置了,现在对之前的基本配置进行代码优化;
写一个读取配置工具
1 package tool; 2 3 import org.hibernate.Session; 4 import org.hibernate.SessionFactory; 5 import org.hibernate.cfg.Configuration; 6 //configuration的工具 7 public final class HibernateUtil { 8 private static SessionFactory sessionFactory; 9 private HibernateUtil(){ 10 11 } 12 public static SessionFactory getSessionFactory() { 13 return sessionFactory; 14 } 15 static{ 16 Configuration cfg = new Configuration().configure(); 17 sessionFactory=cfg.buildSessionFactory(); 18 } 19 public static Session getSession() 20 { 21 return sessionFactory.openSession(); 22 } 23 24 }
在测试类中写一个添加数据和获取数据方法
1 // 获取数据 2 static Admin getAdmin(int id) { 3 Session session = null; 4 try { 5 session = HibernateUtil.getSession(); 6 Admin admin = session.get(Admin.class, id); 7 return admin; 8 } finally { 9 if (session != null) 10 session.close(); 11 } 12 } 13 14 // 添加数据 15 static void addAdmin(Admin admin) { 16 Session session = null; 17 Transaction tx = null; 18 try { 19 session = HibernateUtil.getSession(); 20 tx = session.beginTransaction(); 21 session.save(admin); 22 tx.commit(); 23 } finally { 24 if (session != null) 25 session.close(); 26 } 27 }
剩下的直接调用就行了
1 public static void main(String[] args) { 2 // 创建进行持久化对象 3 // Admin admin = new Admin(); 4 // admin.setUserId(6); 5 // admin.setUserName("李四"); 6 // admin.setUserPwd("456"); 7 // addAdmin(admin); 8 Admin admin1 = getAdmin(1); 9 System.out.println("name["+admin1.getUserName()+"],password["+admin1.getUserPwd()+"]"); 10 }