2010-06-27

Removing JpaTemplate in favor of injected @PersistenceContext

In the previous two articles (Spring, JPA 2.0 & Maven and Spring transaction management) I showed you how to create a project that utilizes Spring 3, JPA 2.0 and Maven, that does not require a server and that offers transaction handling.

However, I used Spring's JpaTemplate which got some attention from Tomek Nurkiewicz who pointed out that this is not really a recommended way of doing it.

The recommended way of handling JPA in your DAO classes is to use an EntityManager injected with JEE's @PersistenceContext annotation.

Let's see what the configuration looks like.


Your Spring beans file


  1. Remove the jpaTemplate bean declaration.
  2. Remove the jpaTemplate bean references.
  3. Add PersistenceAnnotationBeanPostProcessor.

Here's the whole file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx.xsd
           http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="Dogs" />
    </bean>

    <bean id="dogsDao" class="me.m1key.springtx.dao.DogsDaoImpl" />

    <bean id="dogsBean" class="me.m1key.springtx.beans.DogsBean"
        scope="singleton">
        <property name="dogsDao" ref="dogsDao" />
    </bean>

    <tx:annotation-driven transaction-manager="myTransactionManager" />

    <bean id="myTransactionManager"
            class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <bean
        class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
</beans>




Your DAO class


  1. Remove extending JpaDaoSupport.
  2. Add @PersistenceContext injected EntityManager.
  3. Replace getJpaTemplate() with the EntityManager (that's not always a non-brainer).
  4. Make each DAO method @Transactional (you can set its readOnly attribute to true if the method only reads data).


package me.m1key.springtx.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

import me.m1key.springtx.entities.Dog;

public class DogsDaoImpl implements DogsDao {

    @PersistenceContext
    private EntityManager em;

    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public List<Dog> retrieveAllDogs() {
        return em.createQuery("from Dog").getResultList();
    }

    @Transactional(readOnly = true)
    public Long retrieveNumberOfDogs() {
        System.out.println(em);
        return (Long) em.createQuery(
             "select count(d) from Dog d")
                .getSingleResult();
    }

    @Transactional(readOnly = false)
    public void persistDog(Dog dog) {
        em.persist(dog);
    }

}



Summary


We removed an additional thin layer of JpaTemplate.

Many sites (e.g. the official Hibernate site) will tell you you cannot use @PersistenceContext in Java SE applications - well we just did, thanks to Spring (thanks to PersistenceAnnotationBeanPostProcessor).

I got some of the information from the blog by Łukasz.

Download source code for this article

29 comments:

  1. I liked this article. I have tried to do away with JpaTemplate in an app that I had created and instead used entitymanager directly. Unfortunately I get a Session Closed problenm. I have tried many things, including your @Transactional suggestion, but to no avail.
    Any suggestions from you are very helpful.

    ReplyDelete
    Replies
    1. The development of artificial intelligence (AI) has propelled more programming architects, information scientists, and different experts to investigate the plausibility of a vocation in machine learning. Notwithstanding, a few newcomers will in general spotlight a lot on hypothesis and insufficient on commonsense application. machine learning projects for final year In case you will succeed, you have to begin building machine learning projects in the near future.

      Projects assist you with improving your applied ML skills rapidly while allowing you to investigate an intriguing point. Furthermore, you can include projects into your portfolio, making it simpler to get a vocation, discover cool profession openings, and Final Year Project Centers in Chennai even arrange a more significant compensation.

      Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account.

      The Nodejs Projects Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete
  2. I tried that as well. Doesn't work. I solved the problem on Friday (and I thought the solution was a fix in my applicationContext.xml) and then when I got back on Monday to add a couple more DAOs, the problem came right back. I have tried different things, but no luck so far.

    ReplyDelete
  3. I'm sorry, I didn't make myself clear. I was suggesting using eager initialization on the collection that is used after session is closed.

    ReplyDelete
  4. At this point, thanks to your tutorial, I managed to do away with JpaTemplate. However the Session Closed thing is driving me crazy

    ReplyDelete
  5. Thank you. I will mull over your suggestion? Maybe this is what you meant
    "failed to lazily initialize a collection of ... no session or session was closed"
    Actually, my exception is:
    DEBUG: org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolv
    er - Resolving exception from handler [de.berlios.web.AuthenticationCo
    ntroller@8aa935]: DEBUG: org.springframework.web.servlet.DispatcherServlet - Could not complete request
    org.hibernate.SessionException: Session is closed!org.hibernate.SessionException: Session is closed!
    status=[failed: org.hibernate.SessionException: Session is closed

    ReplyDelete
  6. What's in that exception line (in your code I mean)?

    ReplyDelete
  7. should I post the lines of code where the exception occurs?

    ReplyDelete
  8. Sorry, if the code appears mangled. I tried to post the code for the entire class, but there was a character limit.
    Thanks,

    ReplyDelete
  9. I can't see it here for some reason, but I got it on my email. What's inside this method:
    getUserDAOJpa().authenticate(login, password);
    ?

    ReplyDelete
  10. Thanks very much for the help. The code inside the getUserDAOJpa().authenticate(login, password);
    is as follows:

    @Repository("userDAO")
    public class UserDAOJpa implements UserDAO {

    protected static final Logger logger=Logger.getLogger(UserDAOJpa.class);

    //Try this
    @PersistenceContext(type=PersistenceContextType.EXTENDED)
    private EntityManager entityManager;


    public UserDAOJpa(){
    }



    @Transactional (propagation = Propagation.REQUIRES_NEW, readOnly = false)
    public AttUser getByLoginFetchFilters(String login) {
    //List users = jpaTemplate.findByNamedQuery("AttUser.byLoginFetchFilters", login);
    logger.info("UserDAOJpa.java -> EntyityManager em is " + entityManager);
    javax.persistence.Query query = entityManager.createQuery("SELECT u FROM AttUser u LEFT JOIN FETCH u.filters WHERE u.login=?1");
    query.setParameter("login", login);
    List users = query.getResultList();
    logger.info("UserDAOJpa: users is " + users);
    logger.info("UserDAOJpa: the size of the returned users list is " + users.size());
    return users.isEmpty() ? null : users.get(0);
    }



    @SuppressWarnings("unchecked")
    @Transactional (propagation = Propagation.REQUIRES_NEW, readOnly = true)
    public boolean authenticate(String login, String passw) {
    //List users = jpaTemplate.findByNamedQuery("AttUser.byLoginAndHashedPassoword", login, passw);
    //List users = entityManager.createQuery("SELECT u FROM de.berlios.jhelpdesk.model.AttUser u WHERE u.login= :login AND u.passw= :passw").getResultList();
    javax.persistence.Query query = entityManager.createQuery("SELECT u FROM de.berlios.jhelpdesk.model.AttUser u WHERE u.login= :login AND u.passw= :passw");
    query.setParameter("login", login);
    query.setParameter("passw", passw);
    List users = query.getResultList();
    logger.info("UserDAOJpa: users is " + users);
    logger.info("UserDAOJpa: the size of the returned users list is " + users.size());
    return users.isEmpty() ? false : true;

    }


    }

    ReplyDelete
  11. And in the authenticate() method it fails in which line?

    ReplyDelete
  12. To the best of my understanding it does not say where in 'authenticate() in ' it fails.

    This is the exceptions stacktrace which also points to an exception in Authfilter.java deeper in the stack trace.

    org.hibernate.SessionException: Session is closed!
    at org.hibernate.impl.AbstractSessionImpl.errorIfClosed(AbstractSessionImpl.java:72)
    at org.hibernate.impl.SessionImpl.setFlushMode(SessionImpl.java:1314)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect$SessionTransactionData.resetFlushMode(HibernateJpaDialect.java:135)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.cleanupTransaction(HibernateJpaDialect.java:83)
    at org.springframework.orm.jpa.JpaTransactionManager.doCleanupAfterCompletion(JpaTransactionManager.java:542)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.cleanupAfterCompletion(AbstractPlatformTransactionManager.java:1011)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:804)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at $Proxy34.authenticate(Unknown Source)
    at de.berlios.jhelpdesk.web.AuthenticationController.processLogin(AuthenticationController.java:128)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:774)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at de.berlios.jhelpdesk.web.tools.filter.AuthFilter.doFilter(AuthFilter.java:39)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)

    ---------

    I will also post the snippet in AuthFilter where it says it is failing.

    ReplyDelete
  13. To the best of my understanding it does not say where in 'authenticate() in ' it fails.

    This is the exceptions stacktrace which also points to an exception in Authfilter.java deeper in the stack trace.

    org.hibernate.SessionException: Session is closed!
    at org.hibernate.impl.AbstractSessionImpl.errorIfClosed(AbstractSessionImpl.java:72)
    at org.hibernate.impl.SessionImpl.setFlushMode(SessionImpl.java:1314)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect$SessionTransactionData.resetFlushMode(HibernateJpaDialect.java:135)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.cleanupTransaction(HibernateJpaDialect.java:83)
    at org.springframework.orm.jpa.JpaTransactionManager.doCleanupAfterCompletion(JpaTransactionManager.java:542)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.cleanupAfterCompletion(AbstractPlatformTransactionManager.java:1011)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:804)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at $Proxy34.authenticate(Unknown Source)
    at de.berlios.jhelpdesk.web.AuthenticationController.processLogin(AuthenticationController.java:128)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:774)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at de.berlios.jhelpdesk.web.tools.filter.AuthFilter.doFilter(AuthFilter.java:39)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)

    ---------

    I will also post the snippet in AuthFilter where it says it is failing.

    ReplyDelete
  14. To the best of my understanding it does not say where in 'authenticate() in ' it fails.

    This is the exceptions stacktrace which also points to an exception in Authfilter.java deeper in the stack trace.

    org.hibernate.SessionException: Session is closed!
    at org.hibernate.impl.AbstractSessionImpl.errorIfClosed(AbstractSessionImpl.java:72)
    at org.hibernate.impl.SessionImpl.setFlushMode(SessionImpl.java:1314)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect$SessionTransactionData.resetFlushMode(HibernateJpaDialect.java:135)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.cleanupTransaction(HibernateJpaDialect.java:83)
    at org.springframework.orm.jpa.JpaTransactionManager.doCleanupAfterCompletion(JpaTransactionManager.java:542)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.cleanupAfterCompletion(AbstractPlatformTransactionManager.java:1011)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:804)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at $Proxy34.authenticate(Unknown Source)
    at de.berlios.jhelpdesk.web.AuthenticationController.processLogin(AuthenticationController.java:128)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:774)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at de.berlios.jhelpdesk.web.tools.filter.AuthFilter.doFilter(AuthFilter.java:39)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)

    ---------

    I will also post the snippet in AuthFilter where it says it is failing.

    ReplyDelete
  15. To the best of my understanding it does not say where in 'authenticate() in ' it fails.

    This is the exceptions stacktrace which also points to an exception in Authfilter.java deeper in the stack trace.

    org.hibernate.SessionException: Session is closed!
    at org.hibernate.impl.AbstractSessionImpl.errorIfClosed(AbstractSessionImpl.java:72)
    at org.hibernate.impl.SessionImpl.setFlushMode(SessionImpl.java:1314)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect$SessionTransactionData.resetFlushMode(HibernateJpaDialect.java:135)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.cleanupTransaction(HibernateJpaDialect.java:83)
    at org.springframework.orm.jpa.JpaTransactionManager.doCleanupAfterCompletion(JpaTransactionManager.java:542)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.cleanupAfterCompletion(AbstractPlatformTransactionManager.java:1011)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:804)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at $Proxy34.authenticate(Unknown Source)
    at de.berlios.jhelpdesk.web.AuthenticationController.processLogin(AuthenticationController.java:128)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:774)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at de.berlios.jhelpdesk.web.tools.filter.AuthFilter.doFilter(AuthFilter.java:39)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)

    ---------

    I will also post the snippet in AuthFilter where it says it is failing.

    ReplyDelete
  16. To the best of my understanding it does not say where in 'authenticate() in ' it fails.

    This is the exceptions stacktrace which also points to an exception in Authfilter.java deeper in the stack trace.

    org.hibernate.SessionException: Session is closed!
    at org.hibernate.impl.AbstractSessionImpl.errorIfClosed(AbstractSessionImpl.java:72)
    at org.hibernate.impl.SessionImpl.setFlushMode(SessionImpl.java:1314)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect$SessionTransactionData.resetFlushMode(HibernateJpaDialect.java:135)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.cleanupTransaction(HibernateJpaDialect.java:83)
    at org.springframework.orm.jpa.JpaTransactionManager.doCleanupAfterCompletion(JpaTransactionManager.java:542)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.cleanupAfterCompletion(AbstractPlatformTransactionManager.java:1011)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:804)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at $Proxy34.authenticate(Unknown Source)
    at de.berlios.jhelpdesk.web.AuthenticationController.processLogin(AuthenticationController.java:128)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:774)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at de.berlios.jhelpdesk.web.tools.filter.AuthFilter.doFilter(AuthFilter.java:39)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)

    ---------

    I will also post the snippet in AuthFilter where it says it is failing.

    ReplyDelete
  17. Well the best thing you can do is to send me the source code to my email with a test that demonstrates the exception.

    Otherwise you may want to debug to find the exact line where it fails.

    ReplyDelete
  18. Which email id should I send it to?

    ReplyDelete
  19. Hi Michal,

    I read your post and would like to ask why it is not recomended to use JpaTemplate, as Tomek also mentioned.

    Having a look at Spring Recipes: pp.649, there is mentioned the following:
    "For example, in a DAO operation implemented with Hibernate or JPA, you have to open and
    close a session or an entity manager, and begin, commit, and roll back a transaction with the native API".

    As a solution is suggested:
    "Spring’s approach to simplifying an ORM framework’s usage is the same as JDBC’s—by defining
    template classes and DAO support classes."

    I wonder why the use of a JpaTemplate is not a good choice. Any resources about that opinion?

    Thanks.

    ReplyDelete
  20. Hi Chris - basically it's about direct depending on Spring. Read on: http://blog.springsource.com/2007/06/26/so-should-you-still-use-springs-hibernatetemplate-andor-jpatemplate/

    Thanks for visiting the blog. :)

    ReplyDelete
  21. Hey I know this post is old, but I am trying to accomplish the task proposed above. The only difference is I am trying to us tx:advice for setting my transactions instead of direct annotation.

    To get to the point every time I deploy I get an error stating that I must use JTA as my transaction type. When using JpaTemplate Resource_local was fine. What am I missing?

    ReplyDelete
  22. Ok I did get it to work with tx:annotation-driven, sucks I can't use tx:advice with JTA.

    ReplyDelete
  23. Hi NEM, I was on holiday, sorry for not replying. I'm glad you got it sorted and thanks for visiting.

    ReplyDelete

  24. تقدم شركة العطار عدد متنوع من الخدمات المنزلية الهامة والتي لا يستطيع أحد ان يستغني عنها مطلقاً وذلك من خلال عمالة مدربة بشكل مميز ومن خلال أسعار لا تقبل المنافسة نظرا لأنها تناسب كل العملاء
    شركة كشف تسربات المياه بجدة
    ويُعرف تسريب المياه بأنّه خلل يطرأ على توصيلات المياه بمختلف أشكالها، سواء كان ذلك في مواسير الصرف أو أكواعها أو مختلف أجزاء مواسير المياه، ومنها: الحنفيات، والخزانات، والسخانات، فيتسبب ذلك الخلل بخروج المياه من المسار المحدد لها إلى محيط المواسير فتتجمع المياه بالقرب من الأماكن المحيطة بالتسريب كالأرضيات والجدران فتلحق الضرر بها نتيجة تفاعلها مع مواد البناء، وتآكل الحديد وتهالك الخرسانة، وبالتالي تفاقم المشاكل في حال التغاضي عن علاجها
    هناك الآلاف من المبيدات الكيميائية المستخدمة اليوم في المنازل، والمكاتب، والمتاجر، والمزارع وأماكن أخرى، ولكنّها تُعد خطرةً؛ لأنها تسبّب تلوّث الأرض، والهواء، والغذاء، والماء،
    شركة مكافحة حشرات بجدة
    وفي بعض الأحيان تكون خطرة جداً على الأشخاص الذين يستخدمونها، وعلى الكائنات الحية الأخرى المحيطة أيضاً، كما يجب الأخذ بعين الاعتبار قراءة الملصق الموجود على المبيد الحشري، وتجنب تلويث الطعام، والشراب، والأواني وغيرها.

    ReplyDelete