Announcement Announcement Module
Collapse
No announcement yet.
Don't repeat the dao - LazyInitializationException Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Don't repeat the dao - LazyInitializationException

    I'm writing a generic dao similar to http://www.ibm.com/developerworks/ja...enericdao.html. Its not exactly the same but pretty close.

    My implementation of the generic dao will insert and loadAll just fine but calling
    Code:
    public T load(PK id)
    	{
    		if(id == null)
    			return null;
    		T object = (T) getHibernateTemplate().load(type, id);
    		return object;
    	}
    in the generic dao fails with the following error message:
    Code:
    Method threw 'org.hibernate.LazyInitializationException' exception.
    Cannot evaluate my.package.model.Email$$EnhancerByCGLIB$$1a6c105f.toString()
    1. Why do I get this error just for the load(id) method when the other methods work fine?
    2. How do I fix it?

    Any help is greatly appreciated.
    Best Regards,
    Axiopisty

    Here is all my code pertinent to my question:
    Maven Dependencies
    Code:
    <properties>
        <spring.version>2.0.8</spring.version>
        <struts.version>2.1.2</struts.version>
        <hibernate.version>3.2.5.ga</hibernate.version>
       <hibernate.annotations.version>3.3.0.ga</hibernate.annotations.version>
    </properties>
    
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-hibernate3</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-annotations</artifactId>
        <version>${hibernate.annotations.version}</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-commons-annotations</artifactId>
        <version>${hibernate.annotations.version}</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate</artifactId>
        <version>${hibernate.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.struts</groupId>
        <artifactId>struts2-core</artifactId>
        <version>${struts.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.struts</groupId>
        <artifactId>struts2-spring-plugin</artifactId>
        <version>${struts.version}</version>
    </dependency>
    GenericDao Interface:
    Code:
    package my.package.dao;
    
    import java.io.Serializable;
    import java.util.Collection;
    
    public interface Dao <T, PK extends Serializable>
    {
      public PK insert(T object);
      public void update(T object);
      public void insertOrUpdate(T object);
      public void delete(T object);
      public T load(PK id);
      public void insertOrUpdateAll(Collection<T> objects);
      public void deleteAll(Collection<T> objects);
      public Collection<T> loadAll();
    }
    Generic Dao:
    Code:
    package my.package.dao.impl;
    
    import my.package.dao.Dao;
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.Collection;
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
    
    @SuppressWarnings(value = "unchecked")
    public class HibernateDao<T, PK extends Serializable> extends HibernateDaoSupport implements Dao<T, PK>
    {
    	protected Class<T> type;
    
    	public HibernateDao(Class<T> type)
    	{
    		this.type = type;
    	}
    
    	public PK insert(T object)
    	{
    		if(object == null)
    			return null;
    		return (PK) getHibernateTemplate().save(object);
    	}
    
    	public void update(T object)
    	{
    		if(object == null)
    			return;
    		getHibernateTemplate().update(object);
    	}
    
    	public void insertOrUpdate(T object)
    	{
    		if(object == null)
    			return;
    		getHibernateTemplate().saveOrUpdate(object);
    	}
    
    	public void delete(T object)
    	{
    		if(object == null)
    			return;
    		getHibernateTemplate().delete(object);
    	}
    
    	public T load(PK id)
    	{
    		if(id == null)
    			return null;
    		T object = (T) getHibernateTemplate().load(type, id);
    		return object;
    	}
    
    	public void insertOrUpdateAll(Collection<T> objects)
    	{
    		if(objects == null || objects.isEmpty())
    			return;
    		getHibernateTemplate().saveOrUpdateAll(objects);
    	}
    
    	public void deleteAll(Collection<T> objects)
    	{
    		if(objects == null)
    			return;
    		getHibernateTemplate().deleteAll(objects);
    	}
    
    	public Collection<T> loadAll()
    	{
    		Collection<T> objects = (Collection<T>) getHibernateTemplate().loadAll(type);
    		return objects;
    	}
    }
    Entity bean:
    Code:
    package my.package.model;
    
    import my.package.MimeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.EnumType;
    import javax.persistence.Enumerated;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    
    @Entity
    public class Email
    {
    	@Id
    	@GeneratedValue(strategy = GenerationType.AUTO)
    	private Long emailId;
    
    	public Long getEmailId()
    	{
    		return emailId;
    	}
    
    	public void setEmailId(Long emailId)
    	{
    		this.emailId = emailId;
    	}
    
    	private String name;
    
    	public String getName()
    	{
    		return name;
    	}
    
    	public void setName(String name)
    	{
    		this.name = name;
    	}
    
    	private String fromName;
    
    	public String getFromName()
    	{
    		return fromName;
    	}
    
    	public void setFromName(String fromName)
    	{
    		this.fromName = fromName;
    	}
    
    	private String fromEmail;
    
    	public String getFromEmail()
    	{
    		return fromEmail;
    	}
    
    	public void setFromEmail(String fromEmail)
    	{
    		this.fromEmail = fromEmail;
    	}
    
    	private String subject;
    
    	public void setSubject(String subject)
    	{
    		this.subject = subject;
    	}
    
    	public String getSubject()
    	{
    		return subject;
    	}
    
    	@Column(nullable = false, length = 20000)
    	private String body;
    
    	public void setBody(String body)
    	{
    		this.body = body;
    	}
    
    	public String getBody()
    	{
    		return body;
    	}
    
    	@Enumerated(EnumType.STRING)
    	private MimeType mimeType;
    
    	public void setMimeType(MimeType mimeType)
    	{
    		this.mimeType = mimeType;
    	}
    
    	public MimeType getMimeType()
    	{
    		if(mimeType == null)
    			return MimeType.text_plain;
    		return mimeType;
    	}
    }
    Generic Service Interface:
    Code:
    package my.package.service;
    
    import java.io.Serializable;
    import java.util.Collection;
    
    public interface GenericService<T, PK extends Serializable>
    {
    	public PK insert(T event);
    	public void update(T event);
    	public void insertOrUpdate(T event);
    	public void delete(T event);
    	public T load(PK id);
    	public void insertOrUpdateAll(Collection<T> objects);
    	public void deleteAll(Collection<T> objects);
    	public Collection<T> loadAll();
    }
    Generic Service:
    Code:
    package my.package.service.impl;
    
    import my.package.dao.Dao;
    import my.package.service.GenericService;
    import java.io.Serializable;
    import java.util.Collection;
    
    public class GenericServiceImpl<T, PK extends Serializable> implements GenericService<T, PK>
    {
    	protected Class<T> type;
    
    	public GenericServiceImpl(Class<T> type)
    	{
    		this.type = type;
    	}
    
    	public PK insert(T event)
    	{
    		return genericDao.insert(event);
    	}
    
    	public void update(T event)
    	{
    		genericDao.update(event);
    	}
    
    	public void insertOrUpdate(T event)
    	{
    		genericDao.insertOrUpdate(event);
    	}
    
    	public void delete(T event)
    	{
    		genericDao.delete(event);
    	}
    
    	public T load(PK id)
    	{
    		return genericDao.load(id);
    	}
    
    	public void insertOrUpdateAll(Collection<T> objects)
    	{
    		genericDao.insertOrUpdateAll(objects);
    	}
    
    	public void deleteAll(Collection<T> objects)
    	{
    		genericDao.deleteAll(objects);
    	}
    
    	public Collection<T> loadAll()
    	{
    		return genericDao.loadAll();
    	}
    
    	private Dao<T, PK> genericDao;
    
    	public void setGenericDao(Dao<T, PK> genericDao)
    	{
    		this.genericDao = genericDao;
    	}
    }
    Struts 2 Action:
    Code:
    package my.package.action;
    
    import my.package.model.Email;
    import .service.GenericService;
    import java.util.Collection;
    import org.apache.commons.lang.StringUtils;
    
    public class EmailAction extends SessionActionHelper
    {
    	private Collection<Email> emails;
    	private Email email;
    	private Long id;
    
    	public String execute()
    	{
    		emails = emailService.loadAll();
    		return SUCCESS;
    	}
    
    	public String load()
    	{
    		email = emailService.load(id);
    		return SUCCESS;
    	}
    
    	public String update()
    	{
    		emailService.insertOrUpdate(email);
    		return SUCCESS;
    	}
    
    	public void validate()
    	{
    		if(StringUtils.isBlank(email.getName()))
    			setActionError("name", "error.required", "label.email.name");
    		if(StringUtils.isBlank(email.getFromName()))
    			setActionError("fromName", "error.required", "label.email.fromName");
    		if(StringUtils.isBlank(email.getFromEmail()))
    			setActionError("fromEmail", "error.required", "label.email.fromEmail");
    		if(StringUtils.isBlank(email.getBody()))
    			setActionError("body", "error.required", "label.email.body");
    	}
    
    	public Collection<Email> getEmails()
    	{
    		return emails;
    	}
    
    	public Email getEmail()
    	{
    		return email;
    	}
    
    	public void setEmail(Email email)
    	{
    		this.email = email;
    	}
    
    	public Long getId()
    	{
    		return id;
    	}
    
    	public void setId(Long id)
    	{
    		this.id = id;
    	}
    
    	private GenericService<Email, Long> emailService;
    
    	public void setEmailService(GenericService<Email, Long> genericService)
    	{
    		this.emailService = genericService;
    	}
    }
    Spring Configuration:
    Code:
    <bean id="emailDao" class="my.package.dao.impl.HibernateDao">
        <constructor-arg value="my.package.model.Email"/>
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    
    <bean id="emailService" class="my.package.service.impl.GenericServiceImpl">
        <constructor-arg value="my.package.model.Email"/>
        <property name="genericDao" ref="emailDao"/>
    </bean>
    
    <bean id="emailAction" class="my.package.action.EmailAction" scope="prototype">
        <property name="emailService" ref="emailService"/>
    </bean>
    Last edited by axiopisty; Mar 11th, 2009, 09:16 PM. Reason: It's a long post, I'll put the question first to get to the point in consideration of the non-interested readers :D

  • #2
    Replace the load method with the get method

    I found out after doing more research that the load method doesn't really load the object from the database. Instead it automatically returns a proxy object. Load assumes the object has already been "gotten with get" from the database and is in the cache.

    Just use get instead of load if you want to make sure you hit the database, and make sure you know the difference between these 2 methods.

    Cheers.

    Comment


    • #3
      and how do you use it?

      Hi,
      I'm really new to spring/hibernate and I'm trying to understand your code.

      let's say I have changed the load with get and that everything should work... how do I use it in a main method? can you write for the code needed to get an e-mail?

      cheers

      Comment


      • #4
        If you are trying to learn spring have a look at the sample applications that come with it, it should get you started on the right path.

        Comment


        • #5
          Sample of usage in Struts Action

          spring configuration:
          Code:
              <bean id="emailAction" class="your.package.action.EmailAction" scope="prototype">
                  <property name="emailService" ref="emailService"/>
              </bean>
          
              <!--Generic Services-->
              <bean id="emailService" class="your.package.service.GenericServiceImpl">
                  <constructor-arg value="your.package.model.Email"/>
                  <property name="genericDao" ref="emailDao"/>
              </bean>
          
              <!--Abstract Generic Dao-->
              <bean id="dao" abstract="true" class="your.package.dao.HibernateDao">
                  <property name="sessionFactory" ref="sessionFactory"/>
              </bean>
              <bean id="emailDao" parent="dao">
                  <constructor-arg value="your.package.model.Email"/>
              </bean>
          Note, the following Action extends another object in my package that helps with things for Struts 2. You don't need it. This class is just a pojo so if you're trying to copy this code and test with it, just remove the extended Class and any references to it.

          your.package.action.EmailAction:
          Code:
          package your.package.action;
          
          import your.package.model.Email;
          import your.package.service.GenericService;
          import java.util.Collection;
          import org.apache.commons.lang.StringUtils;
          import org.apache.commons.logging.Log;
          import org.apache.commons.logging.LogFactory;
          
          public class EmailAction extends SessionActionHelper
          {
            private static Log log = LogFactory.getLog(EmailAction.class);
          
            private Collection<Email> emails;
            private Email email;
            private Long id;
          
            private GenericService<Email, Long> emailService;
          
            public void setEmailService(GenericService<Email, Long> emailService)
            {
              this.emailService = emailService;
            }
          
            public String execute()
            {
              emails = emailService.loadAll();
              return SUCCESS;
            }
          
            public String load()
            {
              email = emailService.load(id);
              return SUCCESS;
            }
          
            public String update()
            {
              try
              {
                emailService.insertOrUpdate(email);
              }
              catch(Throwable t)
              {
                log.error(t.getMessage(), t);
                return ERROR;
              }
              return SUCCESS;
            }
          
            public String delete()
            {
              try
              {
                Email email = loadById(id);
                if(email != null)
                  emailService.delete(email);
              }
              catch(Throwable t)
              {
                log.error(t.getMessage(), t);
                return ERROR;
              }
              return SUCCESS;
            }
          
            public void validate()
            {
              if(StringUtils.isBlank(email.getName()))
                setActionError("name", "error.required", "label.email.name");
              if(StringUtils.isBlank(email.getFromName()))
                setActionError("fromName", "error.required", "label.email.fromName");
              if(StringUtils.isBlank(email.getFromEmail()))
                setActionError("fromEmail", "error.required", "label.email.fromEmail");
              if(StringUtils.isBlank(email.getBody()))
                setActionError("body", "error.required", "label.email.body");
            }
          
            public Collection<Email> getEmails()
            {
              return emails;
            }
          
            public Email getEmail()
            {
              return email;
            }
          
            public void setEmail(Email email)
            {
              this.email = email;
            }
          
            public Long getId()
            {
              return id;
            }
          
            public void setId(Long id)
            {
              this.id = id;
            }
          
            private Email loadById(Long id)
            {
              if(id == null)
                return null;
          
              if(emails == null)
                return emailService.load(id);
          
              for(Email e : emails)
                if(e.getEmailId().equals(id))
                  return e;
          
              return null;
            }
          }
          your.package.service.GenericServiceImpl:
          Code:
          package your.package.service.impl;
          
          import your.package.dao.Dao;
          import your.package.service.GenericService;
          import java.io.Serializable;
          import java.util.Collection;
          import org.springframework.transaction.annotation.Propagation;
          import org.springframework.transaction.annotation.Transactional;
          
          @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
          public class GenericServiceImpl<T, PK extends Serializable> implements GenericService<T, PK>
          {
            protected Class<T> type;
          
            public GenericServiceImpl(Class<T> type)
            {
              this.type = type;
            }
          
            @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
            public PK insert(T object)
            {
              return genericDao.insert(object);
            }
          
            @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
            public void update(T object)
            {
              genericDao.update(object);
            }
          
            @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
            public void insertOrUpdate(T object)
            {
              genericDao.insertOrUpdate(object);
            }
          
            @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
            public void delete(T object)
            {
              genericDao.delete(object);
            }
          
            @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
            public T load(PK id)
            {
              return genericDao.load(id);
            }
          
            @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
            public Collection<PK> insertAll(Collection<T> objects)
            {
              return genericDao.insertAll(objects);
            }
          
            @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
            public void insertOrUpdateAll(Collection<T> objects)
            {
              genericDao.insertOrUpdateAll(objects);
            }
          
            @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
            public void deleteAll(Collection<T> objects)
            {
              genericDao.deleteAll(objects);
            }
          
            @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
            public Collection<T> loadAll()
            {
              return genericDao.loadAll();
            }
          
            private Dao<T, PK> genericDao;
          
            public void setGenericDao(Dao<T, PK> genericDao)
            {
              this.genericDao = genericDao;
            }
          }
          Let me know how it works out for you! Good luck.

          Comment


          • #6
            I still cannot make it work! here is my relevant code (very similar to yours)

            GenericDAO interface
            PHP Code:
            package ch.orange.rps_ws.dao;

            import java.io.Serializable;
            import java.util.List;


            import java.io.Serializable;
            import java.util.Collection;

            public interface 
            GenericDAO <TPK extends Serializable>
            {
              public 
            PK insert(T object);
              public 
            void update(T object);
              public 
            void insertOrUpdate(T object);
              public 
            void delete(T object);
              public 
            T get(PK id);
              public 
            void insertOrUpdateAll(Collection<Tobjects);
              public 
            void deleteAll(Collection<Tobjects);
              public 
            Collection<TloadAll();

            GenericDAO implementation
            PHP Code:
            package ch.orange.rps_ws.dao.hibernate;

            import ch.orange.rps_ws.dao.GenericDAO;
            import java.io.Serializable;
            import java.util.ArrayList;
            import java.util.Collection;

            import org.hibernate.SessionFactory;
            import org.hibernate.cfg.Configuration;
            import org.springframework.orm.hibernate3.support.HibernateDaoSupport;


            @
            SuppressWarnings(value "unchecked")
            public class 
            GenericDAOImpl<TPK extends Serializable> extends HibernateDaoSupport implements GenericDAO<TPK>
            {
                protected Class<
            Ttype;

                public 
            GenericDAOImpl(Class<Ttype)
                {
                    
            this.type type;
                }

                public 
            PK insert(T object)
                {
                    if(
            object == null)
                        return 
            null;
                    return (
            PKgetHibernateTemplate().save(object);
                }

                public 
            void update(T object)
                {
                    if(
            object == null)
                        return;
                    
            getHibernateTemplate().update(object);
                }

                public 
            void insertOrUpdate(T object)
                {
                    if(
            object == null)
                        return;
                    
            getHibernateTemplate().saveOrUpdate(object);
                }

                public 
            void delete(T object)
                {
                    if(
            object == null)
                        return;
                    
            getHibernateTemplate().delete(object);
                }

                

                public 
            void insertOrUpdateAll(Collection<Tobjects)
                {
                    if(
            objects == null || objects.isEmpty())
                        return;
                    
            getHibernateTemplate().saveOrUpdateAll(objects);
                }

                public 
            void deleteAll(Collection<Tobjects)
                {
                    if(
            objects == null)
                        return;
                    
            getHibernateTemplate().deleteAll(objects);
                }

                public 
            Collection<TloadAll()
                {
                    
            Collection<Tobjects = (Collection<T>) getHibernateTemplate().loadAll(type);
                    return 
            objects;
                }

                public 
            T get(PK id) {
                    if(
            id == null)
                        return 
            null;
                    
            T object = (TgetHibernateTemplate().load(typeid);
                    return 
            object;

                }

            GenericService interface
            PHP Code:
            package ch.orange.rps_ws.service;

            import java.io.Serializable;
            import java.util.Collection;

            public interface 
            GenericService<TPK extends Serializable>
            {
                public 
            PK insert(T event);
                public 
            void update(T event);
                public 
            void insertOrUpdate(T event);
                public 
            void delete(T event);
                public 
            T get(PK id);
                public 
            void insertOrUpdateAll(Collection<Tobjects);
                public 
            void deleteAll(Collection<Tobjects);
                public 
            Collection<TloadAll();

            GenericService Implementation
            PHP Code:
            package ch.orange.rps_ws.service.impl;


            import ch.orange.rps_ws.dao.GenericDAO;
            import ch.orange.rps_ws.service.GenericService;
            import java.io.Serializable;
            import java.util.Collection;

            public class 
            GenericServiceImpl<TPK extends Serializable> implements GenericService<TPK>
            {
                protected Class<
            Ttype;
                private 
            GenericDAO<TPKgenericDao;

                public 
            GenericServiceImpl(Class<Ttype)
                {
                    
            this.type type;
                    
            System.out.println("sono in generic service impl");
                }

                public 
            PK insert(T event)
                {
                    return 
            genericDao.insert(event);
                }

                public 
            void update(T event)
                {
                    
            genericDao.update(event);
                }

                public 
            void insertOrUpdate(T event)
                {
                    
            genericDao.insertOrUpdate(event);
                }

                public 
            void delete(T event)
                {
                    
            genericDao.delete(event);
                }

                public 
            T get(PK id)
                {
                    return 
            genericDao.get(id);
                }

                public 
            void insertOrUpdateAll(Collection<Tobjects)
                {
                    
            genericDao.insertOrUpdateAll(objects);
                }

                public 
            void deleteAll(Collection<Tobjects)
                {
                    
            genericDao.deleteAll(objects);
                }

                public 
            Collection<TloadAll()
                {
                    return 
            genericDao.loadAll();
                }

                public 
            void setGenericDao(GenericDAO<TPKgenericDAO)
                {
                    
            this.genericDao genericDAO;
                }

            Partner domain class
            PHP Code:
            package ch.orange.rps_ws.domain;

            public class 
            Partner {

                private 
            String id;
                private 
            String official_name;
                private 
            String network_name;
                private 
            String handset_display;
                private 
            String web_address;
                private 
            String map_url;
                private 
            String map_code_2g;
                private 
            String map_code_3g;
                private 
            Integer visible;
                
                public 
            String getId() {
                    return 
            id;
                }
                public 
            void setId(String id) {
                    
            this.id id;
                }
                public 
            String getOfficial_name() {
                    return 
            official_name;
                }
                public 
            void setOfficial_name(String official_name) {
                    
            this.official_name official_name;
                }
                public 
            String getNetwork_name() {
                    return 
            network_name;
                }
                public 
            void setNetwork_name(String network_name) {
                    
            this.network_name network_name;
                }
                public 
            String getHandset_display() {
                    return 
            handset_display;
                }
                public 
            void setHandset_display(String handset_display) {
                    
            this.handset_display handset_display;
                }
                public 
            String getWeb_address() {
                    return 
            web_address;
                }
                public 
            void setWeb_address(String web_address) {
                    
            this.web_address web_address;
                }
                public 
            String getMap_url() {
                    return 
            map_url;
                }
                public 
            void setMap_url(String map_url) {
                    
            this.map_url map_url;
                }
                public 
            String getMap_code_2g() {
                    return 
            map_code_2g;
                }
                public 
            void setMap_code_2g(String map_code_2g) {
                    
            this.map_code_2g map_code_2g;
                }
                public 
            String getMap_code_3g() {
                    return 
            map_code_3g;
                }
                public 
            void setMap_code_3g(String map_code_3g) {
                    
            this.map_code_3g map_code_3g;
                }
                public 
            Integer getVisible() {
                    return 
            visible;
                }
                public 
            void setVisible(Integer visible) {
                    
            this.visible visible;
                }
                
                

            Beans.xml (only the relevant part).
            note: I don't have a sessionFactory bean... I think this is what causes the problem.. right?
            Without the genericDAO I could use the db by calling the sessionFactory inside of the code.. how do I do it in beans.xml?
            PHP Code:
            <!--Generic Services-->
                <
            bean id="partnerService" class="ch.orange.rps_ws.service.impl.GenericServiceImpl">
                    <
            constructor-arg value="ch.orange.rps_ws.domain.Partner"/>
                    <
            property name="genericDao" ref="partnerDAO"/>
                </
            bean>

                <!--Abstract 
            Generic Dao-->
                <
            bean id="genericDAO" abstract="true" class="ch.orange.rps_ws.dao.GenericDAO">
                    <
            property name="sessionFactory" ref="sessionFactory"/>
                </
            bean>
                <
            bean id="partnerDAO" parent="genericDAO">
                    <
            constructor-arg value="ch.orange.rps_ws.domain.Partner"/>
                </
            bean
            I also have defined Partner.hbm.xml and hibernate configuration is in hibernate.cfg.xml

            Finally.. here is how I'm trying to test it:
            App
            PHP Code:
            public class App {

                public static 
            void main(String[] args) {

                    
            System.out.println("in app");
                    
                    
            Tester t = new Tester();
                    
            t.test();
                }

            and Tester
            PHP Code:
            import java.util.Collection;

            import ch.orange.rps_ws.domain.Partner;
            import ch.orange.rps_ws.service.GenericService;

            public class 
            Tester {
                
                private 
            GenericService<PartnerStringpartnerService;
                
                public 
            void test(){
                    
                    
            System.out.println("in tester:test");
                    
                    try {
                        
            Collection<Partnerps partnerService.loadAll();
                        
            System.out.println(ps.size());
                        
                    } catch (
            Exception e) {
                        
            // TODO Auto-generated catch block
                        
            e.printStackTrace();
                    }
                }


            but when I try it I get the following exception:

            PHP Code:
            in app
            in tester
            :test
            java
            .lang.NullPointerException
                at ch
            .orange.rps.service.spring.Tester.test(Tester.java:17)
                
            at ch.orange.rps.service.spring.App.main(App.java:31

            meaning that partnerService is not defined... right?
            how can I fix this?

            Thank you very much in advance

            Comment


            • #7
              NullPointerException

              Your code is producing a NullPointerException because you are trying to access the partnerService without initializing it.

              If you are using Spring Injection to set the partnerService in your test class then you will need a setter for the partnerService. However, it looks like you're not using Spring Injection.

              I would recommend doing something like the following assuming that you have Spring configured properly and ready to use.

              ApplicationContext spring = new ClassPathXmlApplicationContext("spring.xml");
              GenericService<Partner, String> partnerService = (GenericService<Partner, String>)spring.getBean("partnerService");

              Those 3 lines of code should initialize your service object successfully if you have properly configured spring into your application (also assuming that the name of your file with your spring bean definitions is called spring.xml) Once you have initialized your bean then you can use it without getting a NullPointerException.

              Also, the HibernateDaoSupport class requires a SessionFactory object. You'll need to define that object in your spring beans definitions if you have not already done so.
              Last edited by axiopisty; Aug 2nd, 2009, 07:34 PM. Reason: Adding information

              Comment


              • #8
                Agree with the previous post, if you want to make this simplier just write a unit tests for this instead. Spring has support classes to aid testing which might make this easier for you.

                Comment


                • #9
                  Guys, thank you for your great help!
                  I thought I had at leas a minimum understanding of spring and Dependency Injection... apparently I don't have a clue!

                  I understand that partnerService is not initialized... and I'm trying to inject it in the Tester class as it is defined in this quick tutorial (http://www.techfaq360.com/tutorial/s...yinjection.jsp).

                  setters added to Tester
                  PHP Code:
                  public void setPartnerService(GenericService<PartnerStringpartnerService) {
                          
                  this.partnerService partnerService;
                      }
                      public 
                  GenericService<PartnerStringgetPartnerService() {
                          return 
                  partnerService;
                      } 
                  Beans.xml (all)
                  PHP Code:
                  <?xml version="1.0" encoding="UTF-8"?>
                  <beans xmlns="http://www.springframework.org/schema/beans"
                         xmlns:context="http://www.springframework.org/schema/context"
                         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                         xmlns:tx="http://www.springframework.org/schema/tx" 
                         xmlns:cxf="http://cxf.apache.org/core"
                         xmlns:jaxws="http://cxf.apache.org/jaxws"
                         xsi:schemaLocation="
                         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
                         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                         http://cxf.apache.org/core
                         http://cxf.apache.org/schemas/core.xsd
                         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
                         http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">


                      <context:component-scan base-package="ch.orange.rps_ws">
                          <context:include-filter type="annotation" expression="javax.jws.WebService" />
                      </context:component-scan>
                      
                      <import resource="classpath:META-INF/cxf/cxf.xml" />
                      <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
                      <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
                      
                      <!-- Enable message logging using the CXF logging feature -->
                      <cxf:bus>
                          <cxf:features>
                              <cxf:logging/>
                          </cxf:features>
                      </cxf:bus>

                      <!--Generic Services-->
                      <bean id="partnerService" class="ch.orange.rps_ws.service.impl.GenericServiceImpl">
                          <constructor-arg value="ch.orange.rps_ws.domain.Partner"/>
                          <property name="genericDao" ref="partnerDAO"/>
                      </bean>

                      <!--Abstract Generic Dao-->
                      <bean id="genericDAO" abstract="true" class="ch.orange.rps_ws.dao.GenericDAO">
                          <property name="sessionFactory" ref="sessionFactory"/>
                      </bean>
                      <bean id="partnerDAO" parent="genericDAO">
                          <constructor-arg value="ch.orange.rps_ws.domain.Partner"/>
                      </bean>
                      
                      <!-- TEMP -->
                      <bean id="Tester" class="ch.orange.rps_ws.service.spring.Tester">
                          <property name="partnerService" ref="partnerService" />
                      </bean>
                      
                      

                      <!-- WEB SERVICE ENDPOINTS -->
                      <jaxws:endpoint 
                        id="helloWorld" 
                        implementor="#helloWorldImpl" 
                        address="/HelloWorld" />
                        
                      <jaxws:endpoint 
                        id="countryService" 
                        implementor="#countryServiceImpl" 
                        address="/CountryService" />

                  </beans>
                  as you see, there is something concerning cxf web services. this works and has nothing to do with the problem.

                  Axiopisty, with this
                  I would recommend doing something like the following assuming that you have Spring configured properly and ready to use.

                  ApplicationContext spring = new ClassPathXmlApplicationContext("spring.xml");
                  GenericService<Partner, String> partnerService = (GenericService<Partner, String>)spring.getBean("partnerService");
                  are you saying that every time I want to use a bean defined in the beans.xml I need to get it with this two lines? I thought spring would take care of that...

                  Comment


                  • #10
                    Originally posted by homer84 View Post
                    are you saying that every time I want to use a bean defined in the beans.xml I need to get it with this two lines? I thought spring would take care of that...
                    No you really don't want to do this often, it's going to create a brand new ApplicationContext and therefore another instance of all your beans. What you want to be doing is creating one applicationContext maybe with something like ContextLoaderListener and then in your Spring configuration wiring all your beans together. You typically shouldn't need to know anything about Spring in your code nor looking up dependencies to other classes.

                    Comment


                    • #11
                      Well... I think I'm going to give up!
                      everything I find on the net explains simple stuff and I don't find an easy way to understand this topic!

                      what should I edit/add in my code to make this work?

                      Comment


                      • #12
                        Ok, I'll give it a last try because I think I'm getting closer but first I need to fix the IoC to be able to continue with the generic dao...
                        I'm trying to understand this by using the official doc (http://static.springsource.org/sprin...#orm-hibernate)

                        my web.xml
                        PHP Code:
                        <?xml version="1.0" encoding="ISO-8859-1"?>

                        <!DOCTYPE web-app
                            PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
                            "http://java.sun.com/dtd/web-app_2_3.dtd">


                        <web-app>
                            <context-param>
                                <param-name>contextConfigLocation</param-name>
                                <param-value>WEB-INF/beans.xml</param-value>
                            </context-param>

                            <listener>
                                <listener-class>
                                    org.springframework.web.context.ContextLoaderListener
                                </listener-class>
                            </listener>

                            <servlet>
                                <servlet-name>CXFServlet</servlet-name>
                                <display-name>CXF Servlet</display-name>
                                <servlet-class>
                                    org.apache.cxf.transport.servlet.CXFServlet
                                </servlet-class>
                                <load-on-startup>1</load-on-startup>
                            </servlet>

                            <servlet-mapping>
                                <servlet-name>CXFServlet</servlet-name>
                                <url-pattern>/*</url-pattern>
                            </servlet-mapping>
                        </web-app>
                        my beans.xml
                        PHP Code:
                        <?xml version="1.0" encoding="UTF-8"?>
                        <beans xmlns="http://www.springframework.org/schema/beans"
                               xmlns:context="http://www.springframework.org/schema/context"
                               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                               xmlns:tx="http://www.springframework.org/schema/tx" 
                               xmlns:cxf="http://cxf.apache.org/core"
                               xmlns:jaxws="http://cxf.apache.org/jaxws"
                               xsi:schemaLocation="
                               http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
                               http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                               http://cxf.apache.org/core
                               http://cxf.apache.org/schemas/core.xsd
                               http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
                               http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">


                            <context:component-scan base-package="ch.orange.rps_ws">
                                <context:include-filter type="annotation" expression="javax.jws.WebService" />
                            </context:component-scan>
                            
                            <import resource="classpath:META-INF/cxf/cxf.xml" />
                            <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
                            <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
                            
                            <!-- Enable message logging using the CXF logging feature -->
                            <cxf:bus>
                                <cxf:features>
                                    <cxf:logging/>
                                </cxf:features>
                            </cxf:bus>
                            
                            <!-- DATABASE -->
                            <!-- DataSource Property -->
                            <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
                             <property name="driverClassName">
                               <value>com.mysql.jdbc.Driver</value>
                             </property>
                             <property name="url">
                               <value>jdbc:mysql://localhost/dbtest</value>
                             </property>
                             <property name="username">
                                 <value>user</value>
                             </property>
                             <property name="password">
                                 <value>pass</value>
                             </property>
                            </bean> 

                            <!-- Database Property -->
                            <bean id="hibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
                             <property name="properties">
                              <props>
                               <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                               <prop key="hibernate.query.substitutions">true 'T', false 'F'</prop>
                               <prop key="hibernate.show_sql">true</prop>
                               <prop key="hibernate.c3p0.minPoolSize">5</prop>
                               <prop key="hibernate.c3p0.maxPoolSize">20</prop>
                               <prop key="hibernate.c3p0.timeout">600</prop>
                               <prop key="hibernate.c3p0.max_statement">50</prop>
                               <prop key="hibernate.c3p0.testConnectionOnCheckout">false</prop>
                              </props>
                             </property>
                            </bean>

                            <!-- Hibernate SessionFactory -->
                            <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
                             <property name="dataSource">
                                 <ref local="dataSource"/>
                             </property>
                             <property name="hibernateProperties">
                                 <ref bean="hibernateProperties" />
                             </property>
                             <!--  OR mapping files. -->
                             <property name="mappingResources">
                                <list>
                                   <value>ch/orange/rps_ws/Country.hbm.xml</value>
                                </list>
                             </property>
                            </bean>
                            
                            <bean id="countryDAO" class="ch.orange.rps_ws.service.dao.hibernate.CountryDAOImpl">
                                <property name="sessionFactory" ref="sessionFactory" />
                            </bean>
                        </beans>
                        my simple CountryDAO implementation
                        PHP Code:
                        package ch.orange.rps_ws.dao.hibernate;

                        import java.util.List;
                        import org.hibernate.SessionFactory;
                        import org.springframework.dao.DataAccessException;
                        import org.springframework.orm.hibernate3.HibernateTemplate;

                        import ch.orange.rps_ws.dao.CountryDAO;
                        import ch.orange.rps_ws.domain.Country;

                        public class 
                        CountryDAOImpl implements CountryDAO {
                            
                            private 
                        HibernateTemplate hibernateTemplate;

                            public 
                        void setSessionFactory(SessionFactory sessionFactory) {
                                
                        this.hibernateTemplate = new HibernateTemplate(sessionFactory);
                            }

                            public List 
                        findAll() throws DataAccessException {
                                
                                List<
                        Country> list = this.hibernateTemplate.find("From Country");
                                return list;
                            }

                        and once again when I test it I get the same nullpoint exception.
                        Why in spring does not inject?

                        Comment


                        • #13
                          I don't really know enough about the WS stuff you're using to help. But generally with Spring there are a couple of things you'll do with dependencies, inject them or look them up. Hence in the earlier examples the collaborators were injected. In your example, you don't want to create a new application context instance as that's going to create another instance of all your beans. What you want to do is either inject the service(s) you want into your bean or if you HAVE to look them up from the application context. The reference manual really is your friend if you are trying to get your head around these issues.
                          http://static.springsource.org/sprin...and-singletons

                          Comment


                          • #14
                            Ok! I finally could solve my issues with the solution presented at the beginning of the post. I had some problems with my dependencies and the beans.xml didn't inject the objects properly.
                            now I can connect to the database and I can get the loadAll method to work.. but when I try the get (genericDAO.load(PK id)) I get the following error:

                            can you help me?

                            25-ago-2009 08:48:51 org.hibernate.LazyInitializationException <init>
                            GRAVE: could not initialize proxy - no Session
                            org.hibernate.LazyInitializationException: could not initialize proxy - no Session
                            at org.hibernate.proxy.AbstractLazyInitializer.initia lize(AbstractLazyInitializer.java:57)
                            at org.hibernate.proxy.AbstractLazyInitializer.getImp lementation(AbstractLazyInitializer.java:111)
                            at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitialize r.invoke(CGLIBLazyInitializer.java:150)
                            at ch.orange.rps_ws.domain.Partner$$EnhancerByCGLIB$$ efcf7821.getOfficial_name(<generated>)
                            at ch.orange.rps_ws.action.impl.PartnerActionImpl.get ById(PartnerActionImpl.java:23)
                            at sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
                            at sun.reflect.NativeMethodAccessorImpl.invoke(Unknow n Source)
                            at sun.reflect.DelegatingMethodAccessorImpl.invoke(Un known Source)
                            at java.lang.reflect.Method.invoke(Unknown Source)
                            at org.apache.cxf.service.invoker.AbstractInvoker.per formInvocation(AbstractInvoker.java:165)
                            at org.apache.cxf.service.invoker.AbstractInvoker.inv oke(AbstractInvoker.java:82)
                            at org.apache.cxf.jaxws.JAXWSMethodInvoker.invoke(JAX WSMethodInvoker.java:54)
                            at org.apache.cxf.service.invoker.AbstractInvoker.inv oke(AbstractInvoker.java:68)
                            at org.apache.cxf.interceptor.ServiceInvokerIntercept or$1.run(ServiceInvokerInterceptor.java:56)
                            at org.apache.cxf.workqueue.SynchronousExecutor.execu te(SynchronousExecutor.java:37)
                            at org.apache.cxf.interceptor.ServiceInvokerIntercept or.handleMessage(ServiceInvokerInterceptor.java:92 )
                            at org.apache.cxf.phase.PhaseInterceptorChain.doInter cept(PhaseInterceptorChain.java:226)
                            at org.apache.cxf.transport.ChainInitiationObserver.o nMessage(ChainInitiationObserver.java:89)
                            at org.apache.cxf.transport.servlet.ServletDestinatio n.invoke(ServletDestination.java:99)
                            at org.apache.cxf.transport.servlet.ServletController .invokeDestination(ServletController.java:305)
                            at org.apache.cxf.transport.servlet.ServletController .invoke(ServletController.java:175)
                            at org.apache.cxf.transport.servlet.AbstractCXFServle t.invoke(AbstractCXFServlet.java:163)
                            at org.apache.cxf.transport.servlet.AbstractCXFServle t.doPost(AbstractCXFServlet.java:141)
                            at javax.servlet.http.HttpServlet.service(HttpServlet .java:637)
                            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:286)
                            at org.apache.coyote.http11.Http11Processor.process(H ttp11Processor.java:845)
                            at org.apache.coyote.http11.Http11Protocol$Http11Conn ectionHandler.process(Http11Protocol.java:583)
                            at org.apache.tomcat.util.net.JIoEndpoint$Worker.run( JIoEndpoint.java:447)
                            at java.lang.Thread.run(Unknown Source)
                            25-ago-2009 08:48:51 org.apache.cxf.phase.PhaseInterceptorChain doIntercept
                            INFO: Application has thrown exception, unwinding now could not initialize proxy - no Session
                            25-ago-2009 08:48:51 org.apache.cxf.interceptor.LoggingOutInterceptor$L oggingCallback onClose

                            Comment


                            • #15
                              Nevermind!
                              I was experiencing the same problem as Axiopisty: needed to use the get and not the load! I think this issue just drove me nuts! eheheh
                              thanks again for your support
                              good work Axiopisty

                              Comment

                              Working...
                              X