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

来源:1-11 通过Hibernate API编写访问数据库的代码

124839

2016-09-18 21:12

试过目前几乎所有看到的代码。仍然报错,都指向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://img.mukewang.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://img.mukewang.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://img.mukewang.com/57de92a50001e76912940598.jpg

写回答 关注

4回答

  • x_bessie
    2017-06-10 14:23:35
    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();
    	}
    
    }


    x_bess...

    我用得是junit 4.4 Hibernate5.0.2 此办法可行,单元测试成功。

    2017-06-10 14:24:39

    共 1 条回复 >

  • _____11_________
    2016-09-29 22:27:05

    强烈好评好评好评

  • 慕粉18453200359
    2016-09-20 15:10:36

    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();
        }
    }

    慕粉1845...

    可以运行的,但是注意hibernate 和jdk的版本的匹配(我的就出了major.minor version 52.0问题。现在用hibernate 5.1.2匹配jdk7 使用),/HibernatePra/src/hibernate.cfg.xml,确认hibernate.cfg.xml的放置位置(我的放在了默认,其它位置的方式还未尝试)。

    2016-09-20 15:14:49

    共 1 条回复 >

  • CRS_0002
    2016-09-18 23:48:18
    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
    	}
    	
    	
    }


Hibernate初探之单表映射

Java持久化框架Hibernate入门教程,掌握Hibernate基本概念

74810 学习 · 793 问题

查看课程

相似问题