Hibernate 4.3.0.Final 获取会话
Posted
技术标签:
【中文标题】Hibernate 4.3.0.Final 获取会话【英文标题】:Hibernate 4.3.0.Final get session 【发布时间】:2014-01-19 03:48:10 【问题描述】:在hibernate documentation for version 4.3.0.Final中给出以下代码sn-p来创建SessionFactory
:
package org.hibernate.tutorial.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory()
try
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
catch (Throwable ex)
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
public static SessionFactory getSessionFactory()
return sessionFactory;
这似乎已经过时,因为 buildSessionFactory()
方法已被弃用。创建SessionFactory
的正确方法是什么?
【问题讨论】:
【参考方案1】:public class TestHB4
private static StandardServiceRegistry serviceRegistry;
private static SessionFactory sessionFactory;
public static void main(String[] args)
Person person = new Person();
person.setFirstName("Namal");
person.setLastName("Dinesh");
Configuration configuration = new Configuration().configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.configure().buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(person);
session.getTransaction().commit();
session.close();
【讨论】:
你能不能也看看我的问题。 ***.com/questions/23646389/… 谢谢! (我想知道他们什么时候决定停止改变这个) 在这个答案中,Configuration.configure()
被调用了两次。因为我认为这可能会导致抛出像Duplicate class/entity mapping
这样的异常,因为配置是被扭曲的。我认为这段代码的第 10 行应该改为sessionFactory = configuration.buildSessionFactory(serviceRegistry);
。如果我错了,请纠正我。以上是关于Hibernate 4.3.0.Final 获取会话的主要内容,如果未能解决你的问题,请参考以下文章
从 Eclipse Luna 卸载 JBoss Tools 4.3.0 Final (Hibernate)
resin发布spring-boot项目报错“java.lang.NoSuchMethodError: org.jboss.logging.Logger.getMessageLogger”
spring和hibernate整合时报sessionFactory无法获取默认Bean Validation factory