我收到此错误:org.hibernate.HibernateException: No CurrentSessionContext configured!
尝试连接到Heroku Postgres DB时。
这是我的hibernate配置(我称之为:hibernateUser.cfg.xml
):
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://ec2-54-243-213-188.compute-1.amazonaws.com:5432/dess6n165jarrv</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.default_schema">dess6n165jarrv</property>
<property name= "hbm2ddl.auto">update</property>
<property name="hibernate.current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
在这里输入代码
我将其实现为单身人士:
public static HibernateUserDAO getInstance(HttpServletResponse response) throws IOException
{
instance = new HibernateUserDAO();
if (instance == null)
{
userFactory = new Configuration().configure("hibernateUser.cfg.xml").addAnnotatedClass(AppUser.class).buildSessionFactory();
}
return instance;
}
public void addNewUser(AppUser user) throws UserExceptionHandler, IOException
{
Session session = null;
int id = 0;
try
{
session = userFactory.getCurrentSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}catch (HibernateException e)
{
if (session.getTransaction() != null) session.getTransaction().rollback();
throw new HibernateException (e);
}finally
{
try
{session.close();}
catch (HibernateException e)
{
throw new UserExceptionHandler("Warnning!! connection did'nt close properly");
}
}
if (id != 0)
System.out.println("User created successfully");
}
enter code here
我在这一行收到错误:
session = userFactory.getCurrentSession();
我认为错误发生在我的配置文件中,但我看不出问题出在哪里(我读了几个例子并将其复制)
答案 0 :(得分:0)
您需要动态设置连接参数:
Map<String,String> jdbcUrlSettings = new HashMap<>();
String jdbcDbUrl = System.getenv("JDBC_DATABASE_URL");
if (null != jdbcDbUrl) {
jdbcUrlSettings.put("hibernate.connection.url", System.getenv("JDBC_DATABASE_URL"));
}
registry = new StandardServiceRegistryBuilder().
configure("hibernate.cfg.xml").
applySettings(jdbcUrlSettings).
build();
这样,它们不是硬编码的,并且会获取平台所做的更改。有关详细信息,请参阅Using the DATABASE_URL with Hibernate。