Hibernate day01(2)

package util;

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

public class HibernateUtils {

	private static SessionFactory factory;
	static{
		factory=new Configuration().configure().buildSessionFactory();
	}
	public static SessionFactory getFactory(){
		return factory;
	}
	
	public static Session getSession(){
		return factory.openSession();
	}
	
	public static void close(Session session){
		if(session!=null){
			session.close();
		}
		
	}
	
}
package test;

import model.Account;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import util.HibernateUtils;

public class AccountTest2 {

	@Test
	public void get(){
		Session session=HibernateUtils.getSession();
		Transaction tx=session.beginTransaction();
		try{
			Account a=(Account)session.get(Account.class, 2);
			System.out.println(a);
			tx.commit();
		}catch(Exception ce){
			tx.rollback();
		}finally{
			HibernateUtils.close(session);
		}
	}
}


你可能感兴趣的:(Hibernate day01(2))