hibernate笔记(一)_补充 Hibnerateutils

HibernateUtils.java

 

package com.goby.Hibernate.bean;



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

public class HibernateUtils {
	private static SessionFactory sessionFatory;
	public static SessionFactory getSessionFatory() {
		return sessionFatory;
	}
	static{
		try{
			Configuration cfg = new Configuration().configure();
			sessionFatory = cfg.buildSessionFactory();
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public static Session getSession(){
		return sessionFatory.openSession();
	}
	
	public static void closeSession(Session session){
		if(session!=null){
			if(session.isOpen()){
				session.close();
			}
		}
	}
	
}

 

Test.java

package test;

import junit.framework.TestCase;

import org.hibernate.Session;

import com.goby.Hibernate.bean.HibernateUtils;
import com.goby.Hibernate.bean.User;

public class test extends TestCase {
	public void testload(){
		Session session = null;
		try{
			
			session = HibernateUtils.getSession();
			session.beginTransaction();
			
			User user = (User)session.get(User.class, 2);
			System.out.println("user.name="+user.getName());
			
			session.getTransaction().commit();
			
		}catch(Exception ex){
			ex.printStackTrace();
			session.getTransaction().rollback();
		}finally{
			HibernateUtils.closeSession(session);
		}
	}
}

 

你可能感兴趣的:(java,Hibernate,bean,JUnit)