hibernate4 获取 sessionfactory

Hibernate4 中 Configuration.buildSessionFactory() 的方法已经标记为过时,官方建议使用:buildSessionFactory(ServiceRegistry serviceRegistry) 这个方法来获取 SessionFactory。估计是和新特性支持多租户有关(没有深入了解,猜测而已)。Hibernate4中获取SessionFactory的方法示例如下:

HibernateTest.java

1    package com.micmiu.hibernate;    
2    
3    import org.hibernate.Session;    
4    import org.hibernate.SessionFactory;    
5    import org.hibernate.cfg.Configuration;    
6    import org.hibernate.service.ServiceRegistry;    
7    import org.hibernate.service.ServiceRegistryBuilder;    
8    
9    import com.micmiu.hibernate.anno.entity.User;    
10    
11    /**    
12     *    
13     * @author <a href="http://www.micmiu.com">Michael Sun</a>    
14     */    
15    public class HibernateTest {    
16    
17        public static void main(String[] args) {    
18            Configuration configuration = new Configuration().configure();    
19            ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()    
20                    .applySettings(configuration.getProperties())    
21                    .buildServiceRegistry();    
22            SessionFactory sessionFactory = configuration    
23                    .buildSessionFactory(serviceRegistry);    
24            Session session = sessionFactory.getCurrentSession();    
25            session.beginTransaction();    
26    
27            User user = new User();    
28            user.setLoginName("micmiu.com");    
29            user.setName("Michael");    
30    
31            session.save(user);    
32    
33            session.getTransaction().commit();    
34            session.close();    
35            sessionFactory.close();    
36    
37        }    
38    }

StandardServiceRegistryBuilder 即可:

1    Configuration config = new Configuration().configure();    
2    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()    
3        .applySettings(config.getProperties()).build();    
4    sessionFactory = config.buildSessionFactory(serviceRegistry);


你可能感兴趣的:(Hibernate4,sessionFactory)