为了账号安全,请及时绑定邮箱和手机立即绑定

究竟该如何创建SessionFactory?(hibernate5.0.x以上版本)

试过目前几乎所有看到的代码。仍然报错,都指向SessionFactory创建的这行。。

  1. 官方那个给的

package test;

import java.io.IOException;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.Test;
import bean.Message;

public class MessageTest {
    private SessionFactory sessionfactory;
    private org.hibernate.Session session;
    private Transaction transaction;
    
    
    @Test
    public void test() throws IOException {
        // 创建一个SessionFactory对象
        SessionFactory sessionFactory = null;
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
        .configure().build();
        try {
        sessionFactory = new MetadataSources(registry).buildMetadata()
        .buildSessionFactory();
        } catch (Exception e) {
        // 出现异常需要销毁StandardServiceRegistry注册表
        StandardServiceRegistryBuilder.destroy(registry);
        System.out.println("创建会化工厂失败");
        }
        //2.创建一个Session对象
        
        org.hibernate.Session session = sessionFactory.openSession();            
        session.beginTransaction();
        
        
//        Configuration configuration = new Configuration().configure();
//        sessionfactory = new Configuration().configure().buildSessionFactory();
//        session = sessionfactory.getCurrentSession();
//        transaction = session.beginTransaction();
        
//        Configuration configuration = new Configuration();
//        SessionFactory sf = configuration.buildSessionFactory();
//        org.hibernate.Session session = sf.openSession();
//        Transaction tx = session.beginTransaction();
//        tx.begin();
        
//        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();  
//        SessionFactory sessionFactory = new MetadataSources(serviceRegistry)  
//                .buildMetadata().buildSessionFactory();  
//        org.hibernate.Session session = sessionFactory.openSession();  
//        Transaction transaction = session.beginTransaction();
    
//          // 创建配置对象
//        Configuration configuration = new Configuration().configure();
//        // 创建服务注册对象
//        StandardServiceRegistryBuilder serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
//        //创建会话工厂对象
//        SessionFactory sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();  
// 
//        //创建会话对象
//        session = sessionfactory.openSession();
//        //开启事务
//        transaction = session.beginTransaction();
        
        Message message = new Message();
        message.setId("1");
        message.setCommand("我是命令");
        message.setContent("呢荣");
        message.setDescription("我是描述");
        session.save(message);
        session.getTransaction().commit();
        session.close();
    }

}

http://img1.sycdn.imooc.com//57de917c00012fe912940598.jpg

2.版本2

package test;

import java.io.IOException;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.Test;
import bean.Message;

public class MessageTest {
    private SessionFactory sessionfactory;
    private org.hibernate.Session session;
    private Transaction transaction;
    
    
    @Test
    public void test() throws IOException {
//        // 创建一个SessionFactory对象
//        SessionFactory sessionFactory = null;
//        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
//        .configure().build();
//        try {
//        sessionFactory = new MetadataSources(registry).buildMetadata()
//        .buildSessionFactory();
//        } catch (Exception e) {
//        // 出现异常需要销毁StandardServiceRegistry注册表
//        StandardServiceRegistryBuilder.destroy(registry);
//        System.out.println("创建会化工厂失败");
//        }
//        //2.创建一个Session对象
//        
//        org.hibernate.Session session = sessionFactory.openSession();            
//        session.beginTransaction();
        
        
//        Configuration configuration = new Configuration().configure();
//        sessionfactory = new Configuration().configure().buildSessionFactory();
//        session = sessionfactory.getCurrentSession();
//        transaction = session.beginTransaction();
        
        Configuration configuration = new Configuration();
        SessionFactory sf = configuration.buildSessionFactory();
        org.hibernate.Session session = sf.openSession();
        Transaction tx = session.beginTransaction();
        tx.begin();
        
//        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();  
//        SessionFactory sessionFactory = new MetadataSources(serviceRegistry)  
//                .buildMetadata().buildSessionFactory();  
//        org.hibernate.Session session = sessionFactory.openSession();  
//        Transaction transaction = session.beginTransaction();
    
//          // 创建配置对象
//        Configuration configuration = new Configuration().configure();
//        // 创建服务注册对象
//        StandardServiceRegistryBuilder serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
//        //创建会话工厂对象
//        SessionFactory sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();  
// 
//        //创建会话对象
//        session = sessionfactory.openSession();
//        //开启事务
//        transaction = session.beginTransaction();
        
        Message message = new Message();
        message.setId("1");
        message.setCommand("我是命令");
        message.setContent("呢荣");
        message.setDescription("我是描述");
        session.save(message);
        session.getTransaction().commit();
        session.close();
    }

}

http://img1.sycdn.imooc.com//57de92110001712212940598.jpg

3.版本3

package test;

import java.io.IOException;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.Test;
import bean.Message;

public class MessageTest {
    private SessionFactory sessionfactory;
    private org.hibernate.Session session;
    private Transaction transaction;
    
    
    @Test
    public void test() throws IOException {
//        // 创建一个SessionFactory对象
//        SessionFactory sessionFactory = null;
//        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
//        .configure().build();
//        try {
//        sessionFactory = new MetadataSources(registry).buildMetadata()
//        .buildSessionFactory();
//        } catch (Exception e) {
//        // 出现异常需要销毁StandardServiceRegistry注册表
//        StandardServiceRegistryBuilder.destroy(registry);
//        System.out.println("创建会化工厂失败");
//        }
//        //2.创建一个Session对象
//        
//        org.hibernate.Session session = sessionFactory.openSession();            
//        session.beginTransaction();
        
        
//        Configuration configuration = new Configuration().configure();
//        sessionfactory = new Configuration().configure().buildSessionFactory();
//        session = sessionfactory.getCurrentSession();
//        transaction = session.beginTransaction();
        
//        Configuration configuration = new Configuration();
//        SessionFactory sf = configuration.buildSessionFactory();
//        org.hibernate.Session session = sf.openSession();
//        Transaction tx = session.beginTransaction();
//        tx.begin();
        
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();  
        SessionFactory sessionFactory = new MetadataSources(serviceRegistry)  
                .buildMetadata().buildSessionFactory();  
        org.hibernate.Session session = sessionFactory.openSession();  
        Transaction transaction = session.beginTransaction();
    
//          // 创建配置对象
//        Configuration configuration = new Configuration().configure();
//        // 创建服务注册对象
//        StandardServiceRegistryBuilder serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
//        //创建会话工厂对象
//        SessionFactory sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();  
// 
//        //创建会话对象
//        session = sessionfactory.openSession();
//        //开启事务
//        transaction = session.beginTransaction();
        
        Message message = new Message();
        message.setId("1");
        message.setCommand("我是命令");
        message.setContent("呢荣");
        message.setDescription("我是描述");
        session.save(message);
        session.getTransaction().commit();
        session.close();
    }

}

http://img1.sycdn.imooc.com//57de92a50001e76912940598.jpg

正在回答

4 回答

public class TestStudents {

	public static SessionFactory getSessionFactory() {

		StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();

		StandardServiceRegistry registry = builder.configure().build();

		SessionFactory sessionFactory = new MetadataSources(registry)
				.buildMetadata().buildSessionFactory();
		System.out.println(sessionFactory);
		return sessionFactory;
	}
		@Test
	public void testSaveStudents()  {

//		Configuration config = new Configuration().configure();
		SessionFactory sessionFactory = null;
		final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
				.configure() // configures settings from hibernate.cfg.xml
				.build();
		try {
			sessionFactory = new MetadataSources(registry).buildMetadata()
					.buildSessionFactory();
		} catch (Exception e) {
			StandardServiceRegistryBuilder.destroy(registry);
		}
	}

	public static void main(String[] args) {
		SessionFactory factory = getSessionFactory();
		Session session = factory.openSession();
		session.getTransaction().begin();
		Students students = new Students("s00000001", "lisa", "女", new Date(),
				"东莞");
		session.save(students);
		session.getTransaction().commit();
		session.close();
		// test();
	}

}


0 回复 有任何疑惑可以回复我~
#1

x_bessie

我用得是junit 4.4 Hibernate5.0.2 此办法可行,单元测试成功。
2017-06-10 回复 有任何疑惑可以回复我~

强烈好评好评好评

0 回复 有任何疑惑可以回复我~

package util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import bean.User;

public class HibernateUtil {

    public static SessionFactory getSessionFactory() {
        
        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
        
        StandardServiceRegistry registry = builder.configure().build();
        
        SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        System.out.println(sessionFactory);
        return sessionFactory;
    }

    public static void test(){
        SessionFactory sessionFactory = null;
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure() // configures settings from hibernate.cfg.xml
                .build();
        try {
            sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
        }
        catch (Exception e) {
            StandardServiceRegistryBuilder.destroy( registry );
        }
    }
    public static void main(String[] args) {
        SessionFactory factory =  getSessionFactory();
        Session session = factory.openSession();
        session.getTransaction().begin();
        User user = new User();
        user.setId(10);
        user.setName("tanlei");
        user.setPassword("123456");
        user.setType("admin");
        session.save(user);
        session.getTransaction().commit();
        session.close();
        //test();
    }
}

0 回复 有任何疑惑可以回复我~
#1

慕粉18453200359

可以运行的,但是注意hibernate 和jdk的版本的匹配(我的就出了major.minor version 52.0问题。现在用hibernate 5.1.2匹配jdk7 使用),/HibernatePra/src/hibernate.cfg.xml,确认hibernate.cfg.xml的放置位置(我的放在了默认,其它位置的方式还未尝试)。
2016-09-20 回复 有任何疑惑可以回复我~
import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Test;

import HibernateTest.Address;
import HibernateTest.Student;

public class TestSession {
	
	
	private SessionFactory sessionfactory;
	private Session session;
	private Transaction transaction;//事务
	
	@Test
	public void testOpenSession(){
		Configuration config = new Configuration().configure();
		sessionfactory= config.buildSessionFactory();
		Session session1 = sessionfactory.openSession();
		Session session2 = sessionfactory.openSession();
		System.out.println(session1==session2);//false
		
	}
	
	@Test
	public void testGetCurrentSession(){
		Configuration config = new Configuration().configure();
		SessionFactory sessionfactory = new  Configuration().configure().buildSessionFactory(new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build());
		Session session1 = sessionfactory.getCurrentSession();
		Session session2 = sessionfactory.getCurrentSession();
		System.out.println(session1==session2);//true
	}
	
	
}


0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

究竟该如何创建SessionFactory?(hibernate5.0.x以上版本)

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信