当前位置: 首页 > 知识库问答 >
问题:

CreateCriteria在没有活动事务的情况下无效(Struts 2.3.15,Spring 3.2.4,Hibernate 4.2.5最终版)

汝昀
2023-03-14

任何人/导师/古鲁可以帮助我解决这个问题?我被困在它超过2天Java代码通过注释

我得到了这个错误createCriteria是无效的没有活动的事务

支柱2.3.15

请参见以下详细错误:

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>

共有3个答案

谭池暝
2023-03-14

如果您在代码中漏掉了这一行,请在编写查询条件之前添加

Transaction tx = session.beginTransaction();

最后

tx.commit();
夏振国
2023-03-14

DAO实现bean通常用@Repository注释。在您的情况下,您使用的是@Component。此原型没有事务支持。

在事务范围内使用Hibernate与数据库进行通信。执行数据库操作需要打开的当前事务。

配置修复程序:

<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory"/>
</bean>

如果使用tx:annotation-driven标记,则必须使用@Transactional注释来注释方法或类。

胡沈义
2023-03-14

没有事务,Hibernate无法工作。使用事务管理器的首选方式。

打电话很简单

session.beginTransaction();
Criteria crit = session.createCriteria();
crit.list();
session.getTransaction().commit();
 类似资料:
  • 问题内容: 我正在通过遵循一个教程来研究示例Spring Hibernate示例,并且陷入了异常说 这是我的代码: Person.java- 简单的POJO person.hbm.xml- 映射文件 PersonDao.java- 我的DAO类 PersonService.java- 服务层 spring-config.xml -Spring配置文件: 最后是我的 主程序-MainApp.java

  • 问题内容: 我正在尝试使用Spring @Transactional批注,但是在调用方法 findAll 时遇到问题,并且出现以下错误: 人DAO: 这是我的: 我尝试删除此行,但是又出现了一个错误,为什么这行不通? 问题答案: 您必须明确声明对事务管理器注释的支持 添加到您的配置中: tx是xmlns:tx =“ http://www.springframework.org/schema/tx”

  • 问题内容: 我正在创建应用程序并在其中使用一些hibernate的东西。我要做的就是将实体保存到数据库中,但我不断收到此异常: 起初,我遇到了这个异常: 然后,我发现需要将其添加到我的hibernate配置中: 这解决了这个问题,但是现在出现了上面的问题。我将实体保存到这样的数据库中: 我的hibernate.cfg.xml文件如下所示: 我在用: Hibernate-4.1.4.Final JD

  • 我已经将Java项目从Eclipse导出为“可运行的JAR文件”,并带有“将所需库提取到生成的JAR中”。当我尝试通过双击启动它时,什么也没有发生,只是文件闪烁。当我尝试像那样从终端运行它时,它工作得很好。

  • 问题内容: 我看到了一些这样的代码: 我以为应该有一个? 为什么这段代码这样做呢? 问题答案: 如果您希望当前执行的方法仍引发异常,同时允许适当地清理资源,则这很有用。下面是处理调用方法中的异常的具体示例。

  • 我们正在进行一项实验,以衡量服务工作者的利益。作为其中的一部分,我们正在记录pageLoadTime和服务工作者状态。其思想是,控制器状态为激活状态的数据将被视为通过服务工作者提供的页面,未安装服务工作者的数据将控制器视为空,因此没有服务工作者状态。这样我们就可以将pageLoadTime与 这是知道该页面由SW提供服务的正确方法吗?我想到的一个问题是,如果SW在两者之间被杀死,并向我们提供错误的