Announcement Announcement Module
Collapse
No announcement yet.
LazyInitializationException Hibernate Spring Help!!! Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • #16
    ok, good luck.

    Comment


    • #17
      I have seen one thing, in docs I have seen this:

      http://static.springsource.org/sprin...iewFilter.html

      Code:
      Servlet 2.3 Filter that binds a Hibernate Session to the thread .....

      what version of servlet are you using?

      and I have seen some spanish and portuguese posts talking about this, and they had similiar problem , solving it changing order of OpenEntityManagerInViewFilter inside web.xml putting it first, and then other delcarations.
      Last edited by duardito; Sep 1st, 2009, 02:13 PM.

      Comment


      • #18
        JPA Hibernate Spring Help!

        Originally posted by duardito View Post
        I have seen one thing, in docs I have seen this:

        http://static.springsource.org/sprin...iewFilter.html

        Code:
        Servlet 2.3 Filter that binds a Hibernate Session to the thread .....

        what version of servlet are you using?

        and I have seen some spanish and portuguese posts talking about this, and they had similiar problem , solving it changing order of OpenEntityManagerInViewFilter inside web.xml putting it first, and then other delcarations.
        Yes I also indicated this in my previous posts,
        I noticed it said servlet 2.3 as well which made me go hmmmm.
        I am using Servlet 2.5 and JSP 2.1.
        Is this a problem?
        I also took the advice of others and have made the OpenEntityManagerInViewFilter the very first thing in my web.xml, observe:
        Code:
        <?xml version="1.0" encoding="UTF-8"?>
        <web-app version="2.5" 
        	xmlns="http://java.sun.com/xml/ns/javaee" 
        	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
          
             <!-- Include this if you are using Hibernate -->
        	<filter>
        	    <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
        	    <filter-class>
        	        org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
        	    </filter-class>
        	      <init-param>
        			<param-name>singleSession</param-name>
        			<param-value>false</param-value>
        		</init-param>
        	    
        	</filter>
        	
        	<filter-mapping>
        	    <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
        	    <url-pattern>/*</url-pattern>
        	</filter-mapping>
        	
          	<listener>
        		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        	</listener>
        	<context-param>
        		<param-name>contextConfigLocation</param-name>
        		<param-value>
        					<!-- classpath:applicationContext.xml  -->
        					<!-- classpath:/data-access-context.xml  -->
        					classpath:data-access-context.xml
        		</param-value>
        	</context-param>
          
        	<welcome-file-list>
        	  <welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
        	</welcome-file-list>
        
            <!-- Spring MVC Configuration -->
            <servlet>
                <servlet-name>dispatcher</servlet-name>
                <servlet-class>
                    org.springframework.web.servlet.DispatcherServlet
                </servlet-class>
                <load-on-startup>2</load-on-startup>
            </servlet>
            <servlet-mapping>
                <servlet-name>dispatcher</servlet-name>
                <url-pattern>*.html</url-pattern>
            </servlet-mapping>
            <servlet-mapping>
                <servlet-name>dispatcher</servlet-name>
                <url-pattern>*.person</url-pattern>
            </servlet-mapping>
            <servlet-mapping>
                <servlet-name>dispatcher</servlet-name>
                <url-pattern>*.tribute</url-pattern>
            </servlet-mapping>
            
        	<jsp-config>
        	    <taglib>
        	      <taglib-uri>/spring</taglib-uri>
        	      <taglib-location>/WEB-INF/spring-form.tld</taglib-location>
        	    </taglib>
        	</jsp-config>
        </web-app>
        Any thoughts or ideas? Thanks a lot.

        Comment


        • #19
          look last post.

          https://forum.hibernate.org/viewtopic.php?f=1&t=986390

          Comment


          • #20
            OpenEntityManagerInViewFilter

            Originally posted by duardito View Post
            Hi, I from that post, I tried this:

            Code:
            	<filter-mapping>
            	    <filter-name>OpenEntityManagerInViewFilter</filter-name>
            	    
                        <servlet-name>dispatcher</servlet-name> 
            	</filter-mapping>
            instead of using <url-pattern>/*</url-pattern> because dispatcher is my spring servlet.
            Code:
                <servlet>
                    <servlet-name>dispatcher</servlet-name>
                    <servlet-class>
                        org.springframework.web.servlet.DispatcherServlet
                    </servlet-class>
                    <load-on-startup>2</load-on-startup>
                </servlet>
            but it didn't work. So I reverted back...
            still stuck...

            Comment


            • #21
              I want to say this.(OpenSessionInViewInterceptor)

              http://72miles.com/blog/spring-opens...ninviewfilter/
              Code:
                	
              <bean id="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
              <property name="sessionFactory">
              <ref bean="factory" />
              </property>
              <property name="singleSession" value="true"/>
              <property name="flushModeName">
              <value>FLUSH_AUTO</value>
              </property>
              
              </bean>

              Comment


              • #22
                OpenEntityManagerInViewFilter problem maaaan!

                Originally posted by duardito View Post
                I want to say this.(OpenSessionInViewInterceptor)

                http://72miles.com/blog/spring-opens...ninviewfilter/
                Code:
                  	
                <bean id="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
                <property name="sessionFactory">
                <ref bean="factory" />
                </property>
                <property name="singleSession" value="true"/>
                <property name="flushModeName">
                <value>FLUSH_AUTO</value>
                </property>
                
                </bean>
                I see what you are saying and incidentally there are 2 ways to "keep the session alive".
                One is what you are saying, using the OpenSessionInViewInterceptor
                The second is: OpenEntityManagerInViewFilter.

                Both can work, I think the OpenSessionInViewFilter would be nicer to use...
                anyway I did this:
                Code:
                	<filter>
                	    <!-- <filter-name>Spring OpenEntityManagerInViewFilter</filter-name> -->
                	    <filter-name>OpenEntityManagerInViewFilter</filter-name>
                	    <filter-class>
                	        org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
                	    </filter-class>
                	      <init-param>
                			<param-name>singleSession</param-name>
                			<param-value>false</param-value>
                		</init-param>
                		<init-param>  
                			<param-name>flushMode</param-name>  
                			<param-value>AUTO</param-value>  
                		</init-param> 
                	    
                	</filter>
                but it still did not work!

                Comment


                • #23
                  I have been dealing with the same issue, my code its almost the same as you have, and i have tried the same things and nothing seems to work, i have found an example which do the same that we want and it works perfectly, and i am pretty confused because it works in the same way.

                  here you can get the code :
                  if in that example you replace PersonAnnotationTest.java for:
                  Code:
                  /*
                  
                  package org.springbyexample.orm.hibernate3.annotation.dao;
                  
                  import static org.junit.Assert.assertEquals;
                  import static org.junit.Assert.assertNotNull;
                  
                  import java.sql.SQLException;
                  import java.util.Collection;
                  
                  import org.junit.Test;
                  import org.junit.runner.RunWith;
                  import org.slf4j.Logger;
                  import org.slf4j.LoggerFactory;
                  import org.springbyexample.orm.hibernate3.annotation.bean.Address;
                  import org.springbyexample.orm.hibernate3.annotation.bean.Person;
                  import org.springframework.beans.factory.annotation.Autowired;
                  import org.springframework.test.context.ContextConfiguration;
                  import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
                  import org.springframework.test.context.transaction.TransactionConfiguration;
                  import org.springframework.transaction.annotation.Transactional;
                  
                  /**
                   * Tests Person DAO.
                   * 
                   * @author David Winterfeldt
                   */
                  @RunWith(SpringJUnit4ClassRunner.class)
                  @ContextConfiguration
                  @TransactionConfiguration
                  public class PersonAnnotationDaoTest {
                  
                      final Logger logger = LoggerFactory.getLogger(PersonAnnotationDaoTest.class);
                      
                      @Autowired
                      protected PersonDao personDao = null;
                  
                      @Test
                      public void testHibernateTemplate() throws SQLException {
                          assertNotNull("Person DAO is null.", personDao);
                          
                          Collection<Person> lPersons = personDao.findPersons();
                  
                          int expected = 2;
                          
                          assertNotNull("Person list is null.", lPersons);
                          assertEquals("Number of persons should be " + expected + ".", expected, lPersons.size());
                          
                          Integer firstId = new Integer(1);
                          Integer secondId = new Integer(2);
                          
                          for (Person person : lPersons) {
                              assertNotNull("Person is null.", person);
                              Collection<Address> ad = person.getAddresses();
                              if (firstId.equals(person.getId())) {                
                                  String firstName = "Joe";
                                  String lastName = "Smith";
                                  
                                  int expectedAddresses = 1;
                  
                              	assertEquals("Person first name should be " + firstName + ".", firstName, person.getFirstName());
                                  assertEquals("Person last name should be " + lastName + ".", lastName, person.getLastName());
                              
                                  assertNotNull("Person's address list is null.", person.getAddresses());
                                  assertEquals("Number of person's address list should be " + expectedAddresses + ".", expectedAddresses, person.getAddresses().size());
                                  
                                  Integer addressId = new Integer(1);
                                  String addr = "1060 West Addison St.";
                                  String city = "Chicago";
                                  String state = "IL";
                                  String zipPostal = "60613";
                                  
                                  for (Address address : person.getAddresses()) {
                                  	assertNotNull("Address is null.", address);
                                  	
                                  	assertEquals("Address id should be '" + addressId + "'.", addressId, address.getId());
                                  	assertEquals("Address address should be '" + address + "'.", addr, address.getAddress());
                                  	
                                  	assertEquals("Address city should be '" + city + "'.", city, address.getCity());
                                  	assertEquals("Address state should be '" + state + "'.", state, address.getState());
                                  	assertEquals("Address zip/postal should be '" + zipPostal + "'.", zipPostal, address.getZipPostal());
                                  }
                              }
                  
                              if (secondId.equals(person.getId())) {                
                                  String firstName = "John";
                                  String lastName = "Wilson";
                                  
                                  int expectedAddresses = 2;
                  
                              	assertEquals("Person first name should be " + firstName + ".", firstName, person.getFirstName());
                                  assertEquals("Person last name should be " + lastName + ".", lastName, person.getLastName());
                              
                                  assertNotNull("Person's address list is null.", person.getAddresses());
                                  assertEquals("Number of person's address list should be " + expectedAddresses + ".", expectedAddresses, person.getAddresses().size());
                  
                                  Integer addressId = new Integer(3);
                                  String addr = "47 Howard St.";
                                  String city = "San Francisco";
                                  String state = "CA";
                                  String zipPostal = "94103";
                  
                                  for (Address address : person.getAddresses()) {
                                  	assertNotNull("Address is null.", address);
                                  	
                                  	if (addressId.equals(address.getId())) {
                  	                	assertEquals("Address id should be '" + addressId + "'.", addressId, address.getId());
                  	                	assertEquals("Address address should be '" + address + "'.", addr, address.getAddress());
                  	                	
                  	                	assertEquals("Address city should be '" + city + "'.", city, address.getCity());
                  	                	assertEquals("Address state should be '" + state + "'.", state, address.getState());
                  	                	assertEquals("Address zip/postal should be '" + zipPostal + "'.", zipPostal, address.getZipPostal());
                                  	}
                                  }
                              }
                  
                              logger.debug(person.toString());
                          }
                      }
                      
                  }

                  change the content of PersonAnnotationDaoTest-context.xml for:
                  Code:
                  <?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: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/tx
                                             http://www.springframework.org/schema/tx/spring-tx.xsd">
                  
                      <import resource="classpath:org/springbyexample/orm/hibernate3/shared-context.xml"/>
                      
                      <!-- Override xml session factory imported from shared-context.xml -->
                      <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
                          <property name="dataSource" ref="dataSource" />
                          <property name="annotatedClasses">
                          	<list>
                          		<value>org.springbyexample.orm.hibernate3.annotation.bean.Person</value>
                          		<value>org.springbyexample.orm.hibernate3.annotation.bean.Address</value>
                          	</list>
                          </property>
                          <property name="hibernateProperties">
                              <value>
                                  hibernate.format_sql=true
                                  hibernate.dialect=org.hibernate.dialect.HSQLDialect
                              </value>
                          </property>
                      </bean>
                      <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
                          <property name="sessionFactory" ref="sessionFactory" />
                      </bean>
                      
                      <tx:annotation-driven/>
                      
                      <bean id="personDao" class="org.springbyexample.orm.hibernate3.annotation.dao.PersonDaoImpl">
                          <property name="sessionFactory" ref="sessionFactory" />
                      </bean>
                  
                  </beans>

                  and in Person.Java you change
                  Code:
                  @OneToMany(fetch=FetchType.EAGER) for @OneToMany(fetch=FetchType.LAZY)
                  and then you run the test you will see that it works just fine.

                  maybe you can see it and try to find if is there any significant difference that we are missing.

                  BR

                  Comment


                  • #24
                    Hello,

                    Sorry to not help you. Unfortunately, I have the same problem with Hibernate 3.3.2.GA, Spring 2.5.6 and JavaConfig 1.0.0.M4. I really do not know where does the problem come from, so I post my entire Hibernate configuration...

                    Configuration
                    Code:
                    @AnnotationDrivenConfig
                    @AnnotationDrivenTx
                    @ComponentScan("ext.comp.app.domain.dao")
                    @Configuration
                    @PropertiesValueSource(locations = "domain.properties")
                    public abstract class DomainContext extends ConfigurationSupport {
                    
                    	/**
                    	 * @return Hibernate template
                    	 */
                    	@Bean
                    	public HibernateTemplate hibernateTemplate() {
                    		HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory(), false);
                    		hibernateTemplate.setCacheQueries(true);
                    		return hibernateTemplate;
                    	}
                    
                    	/**
                    	 * @return Session factory
                    	 */
                    	@Bean
                    	public SessionFactory sessionFactory() {
                    		ComboPooledDataSource dataSource = new ComboPooledDataSource();
                    		// Connexion
                    		try {
                    			dataSource.setDriverClass(Driver.class.getName());
                    		} catch (PropertyVetoException e) {
                    			LOG.fatal(e.getMessage(), e);
                    			throw new RuntimeException(e);
                    		}
                    		dataSource.setJdbcUrl(dbUrlProperty());
                    		dataSource.setPassword(dbPasswordProperty());
                    		dataSource.setUser(dbUserProperty());
                    		// Pool: basic configuration
                    		dataSource.setInitialPoolSize(3);
                    		// Pool: size and connection age
                    		dataSource.setMaxConnectionAge(0);
                    		dataSource.setMaxIdleTimeExcessConnections(0);
                    		// Pool: connection testing
                    		dataSource.setAutomaticTestTable(null);
                    		try {
                    			dataSource.setConnectionTesterClassName(DefaultConnectionTester.class.getName());
                    		} catch (PropertyVetoException e) {
                    			LOG.fatal(e.getMessage(), e);
                    			throw new RuntimeException(e);
                    		}
                    		dataSource.setPreferredTestQuery(null);
                    		dataSource.setTestConnectionOnCheckin(false);
                    		dataSource.setTestConnectionOnCheckout(false);
                    		// Pool: statement pooling
                    		dataSource.setMaxStatementsPerConnection(0);
                    		// Pool: recovery from database outages
                    		dataSource.setAcquireRetryAttempts(30);
                    		dataSource.setAcquireRetryDelay(1000);
                    		dataSource.setBreakAfterAcquireFailure(false);
                    		// Pool: connection lifecycles with connection customizer
                    		dataSource.setConnectionCustomizerClassName(null);
                    		// Pool: unresolved transaction handling
                    		dataSource.setAutoCommitOnClose(false);
                    		dataSource.setForceIgnoreUnresolvedTransactions(false);
                    		// Pool: debug and workaround broken client applications
                    		dataSource.setDebugUnreturnedConnectionStackTraces(false);
                    		dataSource.setUnreturnedConnectionTimeout(0);
                    		// Pool: dataSource
                    		dataSource.setCheckoutTimeout(0);
                    		dataSource.setFactoryClassLocation(null);
                    		dataSource.setMaxAdministrativeTaskTime(0);
                    		dataSource.setUsesTraditionalReflectiveProxies(false);
                    
                    		AnnotationSessionFactoryBean sessionFactoryBean = new AnnotationSessionFactoryBean();
                    		sessionFactoryBean.setDataSource(dataSource);
                    		sessionFactoryBean.setPackagesToScan(new String[] { "ext.comp.app.domain.model" });
                    		Properties hibernateProperties = new Properties();
                    		// Hibernate: basic
                    		hibernateProperties.setProperty("hibernate.dialect", PostgreSQLDialect.class.getName());
                    		hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "validate");
                    		hibernateProperties.setProperty("hibernate.generate_statistics", String.valueOf(dbDebugProperty()));
                    		hibernateProperties.setProperty("hibernate.cache.use_structured_entries", String.valueOf(dbDebugProperty()));
                    		hibernateProperties.setProperty("hibernate.show_sql", String.valueOf(dbDebugProperty()));
                    		hibernateProperties.setProperty("hibernate.format_sql", String.valueOf(false));
                    		hibernateProperties.setProperty("hibernate.use_sql_comments", String.valueOf(dbDebugProperty()));
                    		// Hibernate: cache
                    		hibernateProperties.setProperty("hibernate.cache.provider_class", SingletonEhCacheProvider.class.getName());
                    		hibernateProperties.setProperty("hibernate.cache.use_query_cache", String.valueOf(true));
                    		hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", String.valueOf(true));
                    		hibernateProperties.setProperty("hibernate.cache.use_structured_entries", String.valueOf(dbDebugProperty()));
                    		// Hibernate: connection
                    		hibernateProperties.setProperty("hibernate.connection.autocommit", String.valueOf(false));
                    		hibernateProperties.setProperty("hibernate.connection.release_mode", "on_close");
                    		hibernateProperties.setProperty("hibernate.connection.provider_class", C3P0ConnectionProvider.class.getName());
                    		// Pool: c3p0 properties overrided by Hibernate
                    		hibernateProperties.setProperty("hibernate.c3p0.acquire_increment", String.valueOf(3)); // acquireIncrement
                    		hibernateProperties.setProperty("hibernate.c3p0.idle_test_period", String.valueOf(0)); // idleConnectionTestPeriod
                    		hibernateProperties.setProperty("hibernate.c3p0.timeout", String.valueOf(0)); // maxIdleTime
                    		hibernateProperties.setProperty("hibernate.c3p0.max_size", String.valueOf(15)); // maxPoolSize
                    		hibernateProperties.setProperty("hibernate.c3p0.max_statements", String.valueOf(0)); // maxStatements
                    		hibernateProperties.setProperty("hibernate.c3p0.min_size", String.valueOf(3)); // minPoolSize
                    		// Hibernate: Session
                    		hibernateProperties
                    				.setProperty("hibernate.current_session_context_class", SpringSessionContext.class.getName());
                    		hibernateProperties
                    				.setProperty("hibernate.transaction.factory_class", SpringTransactionFactory.class.getName());
                    		sessionFactoryBean.setHibernateProperties(hibernateProperties);
                    		// Validation
                    		Map<String, ValidateEventListener> eventListeners = new HashMap<String, ValidateEventListener>();
                    		eventListeners.put("pre-update", new ValidateEventListener());
                    		eventListeners.put("pre-insert", new ValidateEventListener());
                    		sessionFactoryBean.setEventListeners(eventListeners);
                    		return (SessionFactory) getConfigured(sessionFactoryBean).getObject();
                    	}
                    
                    	/**
                    	 * Transaction manager for repositories
                    	 * @return Transaction manager
                    	 */
                    	@Bean
                    	public HibernateTransactionManager transactionManager() {
                    		return new HibernateTransactionManager(sessionFactory());
                    	}
                    }
                    DAO
                    Code:
                    /**
                     * Generic DAO implementation for Hibernate
                     */
                    @Repository
                    public final class HibernateTemplateDao extends HibernateDaoSupport implements GenericDao {
                    
                    	/**
                    	 * Constructor
                    	 * @param hibernateTemplate Hibernate template
                    	 */
                    	@Autowired
                    	public HibernateTemplateDao(HibernateTemplate hibernateTemplate) {
                    		setHibernateTemplate(hibernateTemplate);
                    	}
                    
                    	/** {@inheritDoc} */
                    	@Transactional(readOnly = true)
                    	@Override
                    	public <M extends AbstractModel> M read(Class<M> modelClass, Serializable id) {
                    		M m = modelClass.cast(getHibernateTemplate().get(modelClass, id));
                    		if (m == null) {
                    			throw new ObjectRetrievalFailureException(modelClass, id);
                    		}
                    		return m;
                    	}
                    }
                    web.xml
                    Code:
                    <?xml version="1.0" encoding="UTF-8"?>
                    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
                    	<!-- Hibernate session --> 
                        <filter>
                            <filter-name>session</filter-name>
                            <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
                            <init-param>
                    			<param-name>singleSession</param-name>
                    			<param-value>true</param-value>
                    		</init-param>
                    		<init-param>  
                    			<param-name>flushMode</param-name>  
                    			<param-value>AUTO</param-value>  
                    		</init-param>
                        </filter>
                        <filter-mapping>
                            <filter-name>session</filter-name>
                            <url-pattern>/*</url-pattern>
                        </filter-mapping>	
                    </web-app>
                    Should I try the latest Spring 3 development release ?

                    Thank you.

                    Comment


                    • #25
                      lessons learned

                      hey people,

                      I finally managed to help solve this problem with the help of great people like all of you here at Spring Source(Marten Deinum thank you!!) !

                      Here is what the issue was:

                      basically I was defining my transactionManager and my entityManagerFactory twice.

                      This is what was causing confusion for the OpenEntityManagerInViewFilter.

                      What you need to do is define your transactionManager and entityManagerFactory (HibernateSessionFactory I think if non-jpa) one time in your web.xml like so :
                      Code:
                      <listener>
                      		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
                      	</listener>
                      	
                      	<context-param>
                      		<param-name>contextConfigLocation</param-name>
                      		<param-value> 
                      
                      					 classpath:data-access-context.xml 
                      		
                      		</param-value>
                      	</context-param>
                      After that, you can just use the entityManager and transactionManager via DAO's through DI (dependency Injection).
                      Please refer to the next thread I started with the solution:
                      http://forum.springsource.org/showthread.php?t=77300

                      Once again, thank you all for your kind support!
                      LogixPlayer

                      Comment


                      • #26
                        I'm also getting NullPointerException

                        Hello:

                        I'm having the same problem, I've been looking in my configuration files and I don't seem to declare the entityManager twice.
                        I'm using Spring2.5+Jpa(Annotation)+Hibernate with weblogic 9.2.

                        If I pass the entityManager as a parameter from the OpenEntityManagerInViewFilter all works fine which means hibernate is working by if I try to inject the entityManager to de Dao I always get NullPointerException


                        My configuration files are this:


                        My web.xml

                        <?xml version="1.0" encoding="UTF-8"?>
                        <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
                        <display-name>
                        PruebasHibernate</display-name>
                        <welcome-file-list>
                        <welcome-file>index.html</welcome-file>
                        <welcome-file>index.htm</welcome-file>
                        <welcome-file>index.jsp</welcome-file>
                        <welcome-file>default.html</welcome-file>
                        <welcome-file>default.htm</welcome-file>
                        <welcome-file>default.jsp</welcome-file>
                        </welcome-file-list>

                        <filter>
                        <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
                        <filter-class>
                        org.springframework.orm.jpa.support.OpenEntityMana gerInViewFilter
                        </filter-class>
                        </filter>

                        <filter-mapping>
                        <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
                        <url-pattern>/*</url-pattern>
                        </filter-mapping>

                        <servlet>
                        <servlet-name>ServletPersonas</servlet-name>
                        <servlet-class>modelo.servlet.ServletPersonas</servlet-class>
                        </servlet>
                        <servlet-mapping>
                        <servlet-name>ServletPersonas</servlet-name>
                        <url-pattern>/ServletPersonas</url-pattern>
                        </servlet-mapping>
                        <context-param>
                        <param-name>contextConfigLocation</param-name>
                        <param-value>/WEB-INF/applicationContext.xml</param-value>
                        </context-param>

                        <listener><listener-class>org.springframework.web.util.Log4jConfigList ener</listener-class></listener>
                        <listener>
                        <listener-class>org.springframework.web.context.ContextLoade rListener</listener-class>
                        </listener>

                        <!--
                        <listener>
                        <listener-class>org.springframework.web.context.request.Requ estContextListener</listener-class>
                        </listener>
                        -->
                        </web-app>
                        My applicationContext.xml
                        <?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:aop="http://www.springframework.org/schema/aop"
                        xmlns:context="http://www.springframework.org/schema/context"
                        xmlns:tx="http://www.springframework.org/schema/tx"
                        xsi:schemaLocation="
                        http://www.springframework.org/schema/beans http://www.springframework.org/schem...-beans-2.5.xsd
                        http://www.springframework.org/schema/tx http://www.springframework.org/schem...ing-tx-2.5.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
                        <context:annotation-config/>

                        <bean
                        class="org.springframework.orm.jpa.support.Persist enceAnnotationBeanPostProcessor" />

                        <bean id="personaDao" class="modelo.beans.PersonaDao" >

                        </bean>


                        <bean id="entityManagerFactory"
                        class="org.springframework.orm.jpa.LocalContainerE ntityManagerFactoryBean">
                        <property name="persistenceUnitName" value="mysqlPU" />
                        </bean>




                        <bean id="transactionManager"
                        class="org.springframework.orm.jpa.JpaTransactionM anager">
                        <property name="entityManagerFactory" ref="entityManagerFactory" />
                        </bean>

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


                        </beans>
                        PersonaDao.java

                        package modelo.beans;

                        import java.util.ArrayList;

                        import javax.persistence.EntityManager;
                        import javax.persistence.EntityManagerFactory;
                        import javax.persistence.PersistenceContext;
                        import javax.persistence.PersistenceContextType;
                        import javax.servlet.http.HttpServletRequest;

                        import org.springframework.beans.factory.annotation.Autow ired;
                        import org.springframework.orm.jpa.EntityManagerHolder;
                        import org.springframework.stereotype.Repository;
                        import org.springframework.transaction.annotation.Propaga tion;
                        import org.springframework.transaction.annotation.Transac tional;
                        import org.springframework.transaction.support.Transactio nSynchronizationManager;
                        import org.springframework.web.context.WebApplicationCont ext;
                        import org.springframework.web.context.support.WebApplica tionContextUtils;

                        @Repository
                        @Transactional
                        public class PersonaDao {

                        @Autowired
                        @PersistenceContext
                        private EntityManager entityManager;




                        @SuppressWarnings("unchecked")
                        @Transactional
                        public ArrayList<Persona> listarTodos() {
                        ArrayList<Persona> persona=new ArrayList();
                        try
                        {


                        persona= (ArrayList<Persona>) entityManager.createQuery("Select p from Persona p").getResultList();
                        }
                        catch(Exception e)
                        {
                        e.printStackTrace();
                        }
                        finally
                        {}
                        return persona;
                        }


                        }
                        This is a first example project, but we are testing this configuration to chage a production application and we are begining to think it would be best to use Spring+ ibatis.

                        What am I doing wrong?
                        Thanks in advance, Marta.

                        Comment


                        • #27
                          dao nullpointer

                          I am using JPA, my DAO is defined as:
                          public class UserDAO extends JpaDaoSupport.

                          I suppose if you are using straight hibernate there is a HibernateDaoSupport.
                          Essentinally let spring manage the DAO's, you just need to use them.

                          And then this in the xml file:
                          <bean id="UserDAO"
                          class="com.logixplayer.xyz.dao.UserDAO">
                          <property name="entityManagerFactory"
                          ref="entityManagerFactory" />
                          </bean>

                          Hope this helps.

                          Comment


                          • #28
                            I thought that if you use annotations you didn't have to extend from JpaDaoSupport, but I've tried that and I get the same error...

                            Comment


                            • #29
                              Hi.

                              I'm having the same problem a few weeks. I have already submitted questions to the forum, already researched here in the forum, already consulted google. I have not found solution.

                              I changed the association (OneToMany) mapping for bidirectional to unidirectional and could interact in the collection (with LAZY). It was a palliative solution.
                              I am not satisfied. This has to work with spring, but how?

                              Take a look at this same forum (Data Access) in the message with the title is: Problem with associations One-to-many bidirectional. There is more details.

                              I will continue browsing. If find a solution I will inform.

                              Vinicius

                              Comment


                              • #30
                                View Error - Suggestions

                                Hi All,

                                I appear to be having similar issues. I can get my repository classes to run okay, returning all the relevant bits and pieces when called, but when I hand things off to the view I get lazy loading issues.

                                The rest of this post is similar to something I posted to the Click mailing list, as they weren't able to help me.

                                I'm hoping someone can help me this:

                                failed to lazily initialize a collection of role ... no session or session was closed (complete error below)

                                I am using Click 2's SpringClickServlet configured in the web.xml and JPA.

                                This is my web.xml, which seems to load everything okay.


                                <web-app>
                                <listener>
                                <listener-class>org.springframework.web.context.ContextLoade rListener</listener-class>
                                </listener>
                                <servlet>
                                <servlet-name>SpringClickServlet</servlet-name>
                                <servlet-class>au.org.pheno.f1.click.SpringClickServlet</servlet-class>
                                <load-on-startup>0</load-on-startup>
                                </servlet>
                                <servlet-mapping>
                                <servlet-name>SpringClickServlet</servlet-name>
                                <url-pattern>*.htm</url-pattern>
                                </servlet-mapping>
                                </web-app>


                                The page, which is derived from my login page for testing, is trying to load a user (principal) and display its roles to test the lazy loading issue.


                                /*
                                * To change this template, choose Tools | Templates
                                * and open the template in the editor.
                                */
                                package au.org.pheno.f1.test.pages;

                                import javax.annotation.Resource;

                                import org.apache.click.Page;
                                import org.apache.log4j.Logger;
                                import org.springframework.stereotype.Component;

                                import au.org.pheno.f1.domain.attendees.Principal;
                                import au.org.pheno.f1.repository.attendees.IPrincipalRep ository;

                                /**
                                * The login screen provides a user a way to login to the system.
                                *
                                * @author doychi
                                */
                                @Component("au.org.pheno.f1.test.pages.LoginPage")
                                public class LoginPage extends Page {

                                private static final String TITLE = "Test Page";
                                public String msg = "";
                                private IPrincipalRepository repository;
                                private Logger log = Logger.getLogger(LoginPage.class);
                                public Principal principal;

                                private Logger getLogger() {
                                return log;
                                }

                                /**
                                * Retrieve the title
                                *
                                * @return the title
                                */
                                public String getTitle() {
                                return TITLE;
                                }

                                /**
                                * Set the principal repository to use for the page.
                                *
                                * @param principalRepository
                                * the repository to use
                                */
                                @Resource(name = "principalRepository")
                                public void setPrincipalRepository(IPrincipalRepository principalRepository) {
                                if (getLogger().isDebugEnabled()) {
                                getLogger().debug("IPrincipalRepository set");
                                }

                                this.repository = principalRepository;
                                }

                                public IPrincipalRepository getPrincipalRepository() {
                                return repository;
                                }

                                @Override
                                public void onInit() {
                                super.onInit();
                                principal = repository.principalByLogin("admin");
                                getLogger().info(principal.toString());
                                }

                                }


                                The principal repository looks like this:


                                package au.org.pheno.f1.repository.attendees.jpa;

                                import java.util.ArrayList;
                                import java.util.List;
                                import java.util.Map;
                                import java.util.Set;
                                import java.util.TreeMap;

                                import org.apache.commons.lang.StringUtils;
                                import org.apache.commons.lang.builder.ReflectionToString Builder;
                                import org.apache.log4j.Logger;
                                import org.springframework.dao.DataAccessException;
                                import org.springframework.security.AuthenticationService Exception;
                                import org.springframework.security.BadCredentialsExcepti on;
                                import org.springframework.security.userdetails.UserDetai ls;
                                import org.springframework.security.userdetails.UsernameN otFoundException;
                                import org.springframework.stereotype.Component;
                                import org.springframework.transaction.annotation.Transac tional;

                                import au.org.pheno.f1.domain.attendees.Principal;
                                import au.org.pheno.f1.domain.attendees.Role;
                                import au.org.pheno.f1.repository.Repository;
                                import au.org.pheno.f1.repository.WrongNumberOfResultsRet urnedException;
                                import au.org.pheno.f1.repository.attendees.IPrincipalRep ository;

                                /**
                                * Class description
                                *
                                *
                                * @version Enter version here..., 07/12/26
                                * @author Enter your name here...
                                */
                                @Component("principalRepository")
                                @Transactional(readOnly = true)
                                public class PrincipalRepository extends Repository<Principal> implements
                                IPrincipalRepository {

                                private String LOGIN_TAG = "usr";
                                private static final Logger log = Logger
                                .getLogger(PrincipalRepository.class);
                                private static final String FILTER_OP_BOOLEAN = " = ";
                                private static final String FILTER_OP_INTEGER = " = ";
                                private static final String FILTER_OP_STRING = " LIKE ";
                                .
                                .
                                .
                                /**
                                * {@inheritdoc}
                                */
                                @Override
                                public Principal principalByLogin(String login) {
                                Principal result;
                                String query = "SELECT principal FROM PrincipalJpa principal WHERE "
                                + "principal.username = :" + LOGIN_TAG;
                                Map<String, Object> params = new TreeMap<String, Object>();

                                params.put(LOGIN_TAG, login);

                                result = (Principal) readOne(query, params);

                                return result;
                                }
                                .
                                .
                                .
                                }


                                The error appears to be thrown when my template tries to list the roles:


                                <html>
                                <body>
                                <p class="errorMessage">
                                $!msg
                                </p>
                                ${principal.firstName} ${principal.lastName}
                                #foreach( $role in $principal.roles)
                                $role.name
                                #end
                                </body>
                                </html>


                                The error reported is:


                                [Click] [error] handleException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: au.org.pheno.f1.domain.attendees.jpa.PrincipalJpa. registeredForEvents, no session or session was closed
                                at org.hibernate.collection.AbstractPersistentCollect ion.throwLazyInitializationException(AbstractPersi stentCollection.java:358)
                                at org.hibernate.collection.AbstractPersistentCollect ion.throwLazyInitializationExceptionIfNotConnected (AbstractPersistentCollection.java:350)
                                at org.hibernate.collection.AbstractPersistentCollect ion.initialize(AbstractPersistentCollection.java:3 43)
                                at org.hibernate.collection.AbstractPersistentCollect ion.read(AbstractPersistentCollection.java:86)
                                at org.hibernate.collection.PersistentBag.toString(Pe rsistentBag.java:483)
                                at java.lang.String.valueOf(String.java:2838)
                                at java.lang.StringBuffer.append(StringBuffer.java:23 6)
                                at org.apache.commons.lang.builder.ToStringStyle.appe ndDetail(ToStringStyle.java:590)
                                at org.apache.commons.lang.builder.ToStringStyle.appe ndInternal(ToStringStyle.java:465)
                                at org.apache.commons.lang.builder.ToStringStyle.appe nd(ToStringStyle.java:428)
                                at org.apache.commons.lang.builder.ToStringBuilder.ap pend(ToStringBuilder.java:840)
                                at org.apache.commons.lang.builder.ReflectionToString Builder.appendFieldsIn(ReflectionToStringBuilder.j ava:606)
                                at org.apache.commons.lang.builder.ReflectionToString Builder.toString(ReflectionToStringBuilder.java:75 9)
                                at org.apache.commons.lang.builder.ReflectionToString Builder.toString(ReflectionToStringBuilder.java:28 7)
                                at org.apache.commons.lang.builder.ReflectionToString Builder.toString(ReflectionToStringBuilder.java:12 1)
                                at org.apache.commons.lang.builder.ToStringBuilder.re flectionToString(ToStringBuilder.java:126)
                                at au.org.pheno.f1.domain.attendees.jpa.PrincipalJpa. toString(PrincipalJpa.java:655)
                                at au.org.pheno.f1.test.pages.LoginPage.onInit(LoginP age.java:66)
                                at org.apache.click.ClickServlet.processPage(ClickSer vlet.java:512)
                                at org.apache.click.ClickServlet.handleRequest(ClickS ervlet.java:334)
                                at org.apache.click.ClickServlet.doGet(ClickServlet.j ava:253)
                                at javax.servlet.http.HttpServlet.service(HttpServlet .java:617)
                                at javax.servlet.http.HttpServlet.service(HttpServlet .java:717)
                                at org.apache.catalina.core.ApplicationFilterChain.in ternalDoFilter(ApplicationFilterChain.java:290)
                                at org.apache.catalina.core.ApplicationFilterChain.do Filter(ApplicationFilterChain.java:206)
                                at org.apache.catalina.core.StandardWrapperValve.invo ke(StandardWrapperValve.java:233)
                                at org.apache.catalina.core.StandardContextValve.invo ke(StandardContextValve.java:191)
                                at org.apache.catalina.core.StandardHostValve.invoke( StandardHostValve.java:128)
                                at org.apache.catalina.valves.ErrorReportValve.invoke (ErrorReportValve.java:102)
                                at org.apache.catalina.core.StandardEngineValve.invok e(StandardEngineValve.java:109)
                                at org.apache.catalina.connector.CoyoteAdapter.servic e(CoyoteAdapter.java:293)
                                at org.apache.coyote.http11.Http11Processor.process(H ttp11Processor.java:849)
                                at org.apache.coyote.http11.Http11Protocol$Http11Conn ectionHandler.process(Http11Protocol.java:583)
                                at org.apache.tomcat.util.net.JIoEndpoint$Worker.run( JIoEndpoint.java:454)
                                at java.lang.Thread.run(Thread.java:636)



                                Does anyone have any thoughts on what I'm doing wrong?

                                Thanks for any help,
                                --
                                Doychi

                                Comment

                                Working...
                                X