第一個hiberbate的改進

never123450發表於2014-05-08
工具類
package cn.xwy.hibernate;

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 cn.xwy.hibernate;

import java.util.Date;




import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import cn.xwy.hibernate.domain.User;

public class Base {

	public static void main(String[] args) {
		
		
		Session s = HibernateUtil.getSession();
		Transaction tx = s.beginTransaction();
		User user = new User();
		addUser(user);
		System.out.println("end");

	}
	
	static void addUser(User user){
		Session s = null;
		Transaction tx = null;
		try{
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.save(user);
		}catch(HibernateException e){
			if(tx!=null){
				tx.rollback();
				throw e;
			}
		}finally{
			if(s != null)
				s.close();
		}
	}

	static void addUser1(User user){
		Session s = null;
		Transaction tx = null;
		try{
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.save(user);
		}finally{
			if(s != null)
				s.close();
		}
	}
}


相關文章