Hibernate4 中 Configuration.buildSessionFactory() 的方法已经标记为过时,官方建议使用:buildSessionFactory(ServiceRegistry serviceRegistry) 这个方法来获取 SessionFactory ,估计是和新特性支持多租户有关(没有深入了解,猜测而已)。Hibernate4中获取SessionFactory的方法示例如下:
HibernateTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package com.micmiu.hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import com.micmiu.hibernate.anno.entity.User; /** * * @author <a href="http://www.micmiu.com">Michael Sun</a> */ public class HibernateTest { public static void main(String[] args) { Configuration configuration = new Configuration().configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder() .applySettings(configuration.getProperties()) .buildServiceRegistry(); SessionFactory sessionFactory = configuration .buildSessionFactory(serviceRegistry); Session session = sessionFactory.getCurrentSession(); session.beginTransaction(); User user = new User(); user.setLoginName("micmiu.com"); user.setName("Michael"); session.save(user); session.getTransaction().commit(); session.close(); sessionFactory.close(); } } |
@2014-04-29 发现4.3.5的版本中 ServiceRegistryBuilder
也过时不建议用了,直接用
StandardServiceRegistryBuilder
即可:
1 2 3 4 |
Configuration config = new Configuration().configure(); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(config.getProperties()).build(); sessionFactory = config.buildSessionFactory(serviceRegistry); |
本文介绍到此结束@Michael Sun.
原创文章,转载请注明: 转载自micmiu – 软件开发+生活点滴[ http://www.micmiu.com/ ]
本文链接地址: http://www.micmiu.com/j2ee/hibernate/hibernate4-sessionfactory/
0 条评论。