Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

createCriteria is not valid without active transaction (Struts 2.3.15, Spring 3.2.4, Hibernate 4.2.5 Final)

Anybody/Mentors/Guru can help me resolve this issue? I'm stuck for it more than 2 days Java code via annotation

I got this error createCriteria is not valid without active transaction in

Struts 2.3.15 & Spring 3.2.4 & Hibernate 4.2.5 Final

Please see the detailed errors as following:

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 

Stacktraces:

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 layer:

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();

}
 }
}

Service layer-back:

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;
}
 }      
}

Service layer-front:

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());
}
}

Action-back:

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{
     ...
     }
}

Action-front:

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{
     ...
     }
}

All interfaces:

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>
like image 971
Louis Avatar asked Nov 30 '13 05:11

Louis


2 Answers

Hibernate cannot work without transaction. Preferred way to use a transaction manager.

Easy way to just call

session.beginTransaction();
Criteria crit = session.createCriteria();
crit.list();
session.getTransaction().commit();
like image 199
Abhijith Nagarajan Avatar answered Sep 28 '22 13:09

Abhijith Nagarajan


DAO implementation beans are usually annotated with @Repository. In your case you are used a @Component. This stereotype doesn't have a transaction support.

Communication with the database using Hibernate is made in the scope of transaction. An open current transaction is required to perform database operations.

Configuration fixes:

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

and if you use tx:annotation-driven tag then you have to annotate your methods or classes with @Transactional annotation.

like image 37
Roman C Avatar answered Sep 28 '22 11:09

Roman C