hibernate---“helloword”程序--优化,标准写法
新建一个HibernateUtil类
用于程序启动时打开hibernate连接。不用每次都要写代码连接。节省系统开支。
package com.test.hibernateUtil;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtil {private static SessionFactory sessionFactory;private HibernateUtil(){}static {Configuration cfg= new Configuration();cfg.configure();sessionFactory=cfg.buildSessionFactory();}public static SessionFactory getSessionFactory(){return sessionFactory;}public static Session getSession(){return sessionFactory.openSession();}}
package com.test.main;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.Transaction;import com.test.hibernate.User;import com.test.hibernateUtil.HibernateUtil;public class TestHibernate {/** * @param args */public static void main(String[] args) {User user = new User();try{user.setName("wqy1");user.setPassword("1234");if(addUser(user))System.out.println("success add user--id="+user.getId()+" name="+user.getName()+" password="+user.getPassword());}catch(Exception e){e.printStackTrace();//抛出异常}}public static boolean addUser(User user){Session session=null;Transaction ta=null;boolean result=false;try{session = HibernateUtil.getSession();ta = session.beginTransaction();session.save(user);ta.commit();result=true;}catch(HibernateException he){if(ta!=null)ta.rollback();throw he;}finally{if(session!=null)session.close();}return result;}}