我是Hibernate的新手。
尝试从数据库中获取对象但收到错误:
Exception in thread "pool-1-thread-1" org.hibernate.HibernateException: get is not valid without active transaction
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:297)
获得一个对象:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
CallInfo ci = (CallInfo) session.get(CallInfo.class, ucid);
的hibernate.cfg.xml
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sochi_feedback</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>
<property name="hibernate.current_session_context_class">thread</property>
答案 0 :(得分:14)
添加
Transaction tx = session.beginTransaction();
//此声明将启动交易
在CallInfo ci = (CallInfo) session.get(CallInfo.class, ucid);
并在您的交易结束时通过调用..
提交更改tx.commit();
答案 1 :(得分:5)
另一种解决方案是使用openSession()
代替getCurrentSession()
。然后,只有在更新查询时才能使用事务。
Session session = HibernateUtil.getSessionFactory().openSession();
CallInfo ci = (CallInfo) session.get(CallInfo.class, ucid);
答案 2 :(得分:0)
即使在beginTransaction()
和commit()
之后仍然可以获得
Caused by: org.hibernate.HibernateException: setDefaultReadOnly is not valid without active transaction
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)
转到“开始”并搜索服务并重新启动数据库服务
答案 3 :(得分:0)
在实际开始交易之前,您需要在创建sessionFactory之后立即调用session.beginTransaction()
来启动会话。