欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hibernate第二次作业---SessionFactory

程序员文章站 2022-06-02 16:01:33
...

第二次作业:

package com.Entity.Util;

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

public class SessionFactiryUtil {
	   //声明一个私有的静态final类型的Configuration对象
    private static final Configuration config;
    //声明一个私有的静态final类型的SessionFactory对象
    private static final SessionFactory factory;
    //通过静态代码块构建SessionFactory
    static {    	   
		config=new Configuration().configure();
		factory=config.buildSessionFactory();
    }
    //提供一个共有的静态方法供外部获取,并返回一个session对象
   
	public static Session getSession() {
		// TODO Auto-generated method stub
		return factory.openSession();
		//return null;
	}

	        
}


package com.Entity.Util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import com.Entity.User.User;

public class TestSessionFactory {
	Configuration cfg = null;
	SessionFactory sf = null;
	Session s = null;
	Transaction ts = null;

	@Test
	public void add(){
		try {	
		s=SessionFactiryUtil.getSession();
		ts=s.beginTransaction();
		User user=new User();
		user.setUserName("hia2");
		user.setPassword("hia2");
		user.setGender("2");

		s.save(user);
		ts.commit();
	} catch (HibernateException e) {
		if(ts != null)
		{
			ts.rollback();
		}
		e.printStackTrace();
	}finally{
		if(s != null){
			s.close();
		}
	}

	}	
}

Hibernate第二次作业---SessionFactory

参考文章:https://blog.csdn.net/qq_22075041/article/details/76167094点击打开链接

                 https://blog.csdn.net/sunyujia/article/details/2549564点击打开链接