我收到此错误
createCriteria is not valid without active transaction
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>
如果没有事务,Hibernate 就无法工作。使用事务管理器的首选方式。
只需拨打电话即可轻松
session.beginTransaction();
Criteria crit = session.createCriteria();
crit.list();
session.getTransaction().commit();
DAO 实现 bean 通常用
@Repository
进行注释。在你的情况下,你使用的是@Component
。这种构造型没有事务支持。
使用Hibernate与数据库的通信是在事务范围内进行的。执行数据库操作需要打开当前事务。
配置修复:
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
如果您使用
tx:annotation-driven
标签,那么您必须使用 @Transactional
注释来注释您的方法或类。
如果您在代码中错过了这一行,请在编写条件查询之前添加
Transaction tx = session.beginTransaction();
终于
tx.commit();
getCurrentSession()
:获取当前会话。
创建一个与上下文会话不同的新会话
openSession()
:返回:创建的会话。
所需步骤:
以这种方式获取会话:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
初始化交易
Transaction tx = session.beginTransaction();
关闭初始化的交易。
tx.close();