如果没有活动事务,createCriteria 无效(Struts 2.3.15、Spring 3.2.4、Hibernate 4.2.5 Final)
Posted
技术标签:
【中文标题】如果没有活动事务,createCriteria 无效(Struts 2.3.15、Spring 3.2.4、Hibernate 4.2.5 Final)【英文标题】:createCriteria is not valid without active transaction (Struts 2.3.15, Spring 3.2.4, Hibernate 4.2.5 Final) 【发布时间】:2013-12-16 07:27:02 【问题描述】:任何人/导师/大师可以帮助我解决这个问题?我被困了超过2天 Java 代码通过注解
我收到了这个错误createCriteria is not valid without active transaction
in
Struts 2.3.15 & Spring 3.2.4 & Hibernate 4.2.5 Final
请查看详细错误信息如下:
Struts Problem Report
Struts has detected an unhanded exception:
Messages: createCriteria is not valid without active transaction
File: org/hibernate/context/internal/ThreadLocalSessionContext.java
Line number: 348
堆栈跟踪:
org.hibernate.HibernateException: createCriteria is not valid without active transaction
org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:348)
$Proxy35.createCriteria(Unknown Source)
org.zenith.dao.impl.AnswerDAOImpl.listAll(AnswerDAOImpl.java:87)
org.zenith.service.aft.impl.AftAnswerServiceImpl.list(AftAnswerServiceImpl.java:35)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
$Proxy23.list(Unknown Source)
org.zenith.action.aft.AftAnswerAction.list(AftAnswerAction.java:60)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450)
com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)
org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:167)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:252)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:161)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:563)
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
java.lang.Thread.run(Thread.java:722)
applicationContext.xml
:
<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<propertyname="url"value="jdbc:mysql://localhost:3306/sshannotation"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<context:annotation-config>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="*add*" propagation="REQUIRED" />
<tx:method name="set*" propagation="REQUIRED" />
<tx:method name="insert"propagation="REQUIRED" />
<tx:method name="*save*" propagation="REQUIRED" />
<tx:method name="do*" propagation="REQUIRED" />
<tx:method name="register*" propagation="REQUIRED" />
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(* org.zenith.service.*.impl.*.*(..))" id="allManagerMethods" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethods" />
</aop:config>
</context:annotation-config>
<context:component-scan base-package="org.zenith.action.aft,
org.zenith.action.fore,org.zenith.dao.impl,
org.zenith.service.aft.impl,org.zenith.service.fore.impl">
</context:component-scan>
<bean name="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource">
<property name="hibernateProperties">
<props>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>org.zenith.hibernatereverse.pojo.Question</value> <value>org.zenith.hibernatereverse.pojo.Answer</value>
</list>
</property>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
<bean name="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory">
<property name="autodetectDataSource" value="false"/>
</bean>
</beans>
DAO 层:
package org.zenith.dao.impl;
@Component
public class AnswerDAOImpl implements IAnswerDAO
private SessionFactory sessionFactory;
@Autowired
public void setSessionFactory(SessionFactory sessionFactory)
this.sessionFactory = sessionFactory;
public List<Answer> listAll(String column, String keyWord, int currentPage,
int lineSize) throws Exception
return this.sessionFactory.getCurrentSession() .createCriteria(Answer.class).add(Restrictions.like (column, "%"+keyWord+"%")).addOrder(Order.desc("retdate")).setFirstResult((currentPage- 1)*lineSize).setMaxResults(lineSize).list();
服务层返回:
package org.zenith.service.aft.impl;
@Service
public class AftAnswerServiceImpl implements IAftAnswerService
private IAnswerDAO answerDAO;
private IQuestionDAO questionDAO;
@Resource(name="questionDAOImpl")
public void setQuestionDAO(IQuestionDAO questionDAO)
this.questionDAO = questionDAO;
@Resource(name="answerDAOImpl")
public void setAnswerDAO(IAnswerDAO answerDAO)
this.answerDAO = answerDAO;
public Map<String, Object> list(String column, String keyWord,
int currentPage, int lineSize) throws Exception
Map<String,Object> map=new HashMap<String,Object>();
map.put("allAnswers", this.answerDAO.listAll(column, keyWord,currentPage,
lineSize));
map.put("answerCount",this.answerDAO.getAllCount(column, keyWord));
return map;
服务层前端:
package org.zenith.service.fore.impl;
@Service
public class ForeAnswerServiceImpl implements IForeAnswerService
private IAnswerDAO answerDAO;
private IQuestionDAO questionDAO;
@Resource(name="questionDAOImpl")
public void setQuestionDAO(IQuestionDAO questionDAO)
this.questionDAO = questionDAO;
@Resource(name="answerDAOImpl")
public void setAnswerDAO(IAnswerDAO answerDAO)
this.answerDAO = answerDAO;
public boolean insert(Answer vo) throws Exception
return this.answerDAO.doCreate(vo) &&this.questionDAO.updateCount(vo.getQuestion().getQid());
操作返回:
package org.zenith.action.aft;
@SuppressWarnings("serial")
@Repository
@Scope(value="prototype")
public class ForeAnswerAction extends ActionSupport
private IForeAnswerService foreAnswerService;
private Answer answer=new Answer();
@Resource(name="foreAnswerServiceImpl")
public void setForeAnswerService(IForeAnswerService foreAnswerService)
this.foreAnswerService = foreAnswerService;
public Answer getAnswer()
return answer;
public String insert() throws Exception
...
行动前线:
package org.zenith.action.fore;
@SuppressWarnings("serial")
@Repository
@Scope(value="prototype")
public class ForeAnswerAction extends ActionSupport
private IForeAnswerService foreAnswerService;
private Answer answer=new Answer();
@Resource(name="foreAnswerServiceImpl")
public void setForeAnswerService(IForeAnswerService foreAnswerService)
this.foreAnswerService = foreAnswerService;
public Answer getAnswer()
return answer;
public String insert() throws Exception
...
所有接口:
package org.zenith.idao;
public interface IAnswerDAO extends IDAO<Answer, Integer>
public List<Answer> listAll(String column, String keyWord, int currentPage,
int lineSize) throws Exception;
public int getAllCount(String column,String keyWord) throws Exception;
public interface IDAO<T,K>
public boolean doRemove(K id) throws Exception;
public List<T> findAll(String keyWord) throws Exception;
public List<T> findAll(String keyWord,int currentPage,int lineSize) throws Exception;
struts.xml
:
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<constant name="struts.devMode" value="true" />
<constant name="struts.objectFactory" value="spring"/>
<constant name="struts.objectFactory.spring.autoWire" value="name"/>
<constant name="struts.action.extension" value="do,action,go"/>
<package name="base" namespace="/" extends="struts-default">
<global-results>
<result name="forward">/forward.jsp</result>
</global-results>
</package>
<package name="root" namespace="/" extends="base">
</package>
<package name="fore" namespace="/jsp/fore" extends="base">
<action name="foreQuestionAction_*" class="foreQuestionAction" method="1">
<result name="show">/jsp/fore/question/question_show.jsp</result>
</action>
<action name="foreAnswerAction_*" class="foreAnswerAction" method="1">
</action>
</package>
<package name="aft" namespace="/jsp/aft" extends="base">
<action name="aftQuestionAction_*" class="aftQuestionAction" method="1">
<result name="list">/jsp/aft/question/question_list.jsp</result>
</action>
<action name="aftAnswerAction_*" class="aftAnswerAction" method="1">
<result name="list">/jsp/aft/answer/answer_list.jsp</result>
</action>
</package>
</struts>
【问题讨论】:
我的 applicationContext.xml: 你能发布你的代码吗 代码贴如上,java代码通过注解 嗨 Suganthan:我进来了,我的问题需要重新提交吗? 【参考方案1】:Hibernate 不能在没有事务的情况下工作。使用事务管理器的首选方式。
简单的调用方式
session.beginTransaction();
Criteria crit = session.createCriteria();
crit.list();
session.getTransaction().commit();
【讨论】:
我使用sessionFactory的Ioc如上3://DAO层和applicationConetxt.xml配置 同上applicationContext.xml,事务由org.springframework.orm.hibernate4.HibernateTransactionManager管理 任何解决方案,Abhijith?【参考方案2】:如果您在代码中遗漏了这一行,请在编写条件查询之前添加
Transaction tx = session.beginTransaction();
终于
tx.commit();
【讨论】:
其实我在DAO层设置了sessionFactory,sessionFactory的Ioc 事务由我的 applicationContext.xml 上面的 org.springframework.orm.hibernate4.HibernateTransactionManager 管理 使用 spring Hibernate 事务管理器。参考***.com/questions/13087928/…链接 我是否错过了我的 applicationContext.xml 中的某些内容?如果我错过了什么,您能纠正我吗? Suganthan 的地方,抱歉误会刚才谁说的了;无论如何,Suganthan,你有什么办法可以帮我摆脱困境吗?【参考方案3】:DAO 实现 bean 通常使用 @Repository
进行注释。在您的情况下,您使用的是@Component
。这个原型没有事务支持。
使用 Hibernate 与数据库的通信是在事务范围内进行的。执行数据库操作需要一个打开的当前事务。
配置修复:
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
如果您使用tx:annotation-driven
标签,那么您必须使用@Transactional
注释来注释您的方法或类。
【讨论】:
谢谢 Roman,我将尝试使用 @Repository 而不是 @Component 如果DAO使用@Repository注解,Action层应该正确使用什么注解,Roman? 不起作用,如果在 DAO 上使用 @Respository 而不是 @Component,仍然会得到“createCriteria is not valid without active transaction” 看到更新我没有描述 aop-driven 和 annotation-driven 之间的太大区别,参考Spring。 谢谢大家,谢谢大家--只需在hibernate.cfg.xml上配置---getCurrentSession()
:获取当前会话。
创建一个不同于上下文会话的新会话
openSession()
:返回:创建的会话。
【讨论】:
【参考方案5】:需要的步骤:
以这种方式获取会话:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
初始化事务
Transaction tx = session.beginTransaction();
编写条件以从数据库中获取列表。
关闭已初始化的事务。
tx.close();
【讨论】:
以上是关于如果没有活动事务,createCriteria 无效(Struts 2.3.15、Spring 3.2.4、Hibernate 4.2.5 Final)的主要内容,如果未能解决你的问题,请参考以下文章