Sunday 20 January 2013

fetchtype hibernate annotation


//Address.java

package com.hibernate.model;

import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class Address {
      @Column(name = "STREET_NAME")
      private String street;
      @Column(name = "CITY_NAME")
      private String city;
      @Column(name = "DISTRICT_NAME")
      private String district;
      @Column(name = "COUNTRY_NAME")
      private String country;
      @Column(name = "POSTAL_CODE")
      private Integer postalcode;

      public String getStreet() {
            return street;
      }

      public void setStreet(String street) {
            this.street = street;
      }

      public String getCity() {
            return city;
      }

      public void setCity(String city) {
            this.city = city;
      }

      public String getDistrict() {
            return district;
      }

      public void setDistrict(String district) {
            this.district = district;
      }

      public String getCountry() {
            return country;
      }

      public void setCountry(String country) {
            this.country = country;
      }

      public Integer getPostalcode() {
            return postalcode;
      }

      public void setPostalcode(Integer postalcode) {
            this.postalcode = postalcode;
      }

}


UserDetails.java

package com.hibernate.model;

import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Table;

@Entity
@Table(name = "userdetails")
public class UserDetails {
      @Id
      @GeneratedValue
      private Integer userId;
      private String userName;
      @ElementCollection(fetch=FetchType.EAGER)
      @JoinTable(name="USER_ADDRESS",joinColumns=@JoinColumn(name="USER_ID"))
      private Collection<Address> listOfAddresses = new ArrayList<Address>();

     


      public Collection<Address> getListOfAddresses() {
            return listOfAddresses;
      }

      public void setListOfAddresses(Collection<Address> listOfAddresses) {
            this.listOfAddresses = listOfAddresses;
      }

      public Integer getUserId() {
            return userId;
      }

      public void setUserId(Integer userId) {
            this.userId = userId;
      }

      public String getUserName() {
            return userName;
      }

      public void setUserName(String userName) {
            this.userName = userName;
      }

}


UserAccess.java
package com.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.hibernate.model.Address;
import com.hibernate.model.UserDetails;

public class UserAccess {

      public static void main(String[] args) {
            // TODO Auto-generated method stub
            UserDetails user = new UserDetails();
            user.setUserName("karthik reddy");
            Address address1 = new Address();
            address1.setStreet("A");
            address1.setCity("Irala");
            address1.setDistrict("Chittoor");
            address1.setCountry("India");
            address1.setPostalcode(517130);
           
            Address address2 = new Address();
            address2.setStreet("B");
            address2.setCity("Kanipakam");
            address2.setDistrict("Chittoor1");
            address2.setCountry("India");
            address2.setPostalcode(517135);
           
            user.getListOfAddresses().add(address1);
            user.getListOfAddresses().add(address2);
            SessionFactory factory = new Configuration().configure()
                        .buildSessionFactory();
            Session session = factory.openSession();
            session.beginTransaction();
        session.save(user);
            session.getTransaction().commit();
            session.close();
            user=null;
            session=factory.openSession();
            user=(UserDetails)session.get(UserDetails.class,1);
            session.close();
            System.out.println(user.getListOfAddresses().size());
          factory.close();
      }

}



hibernate.cfg.xml  

     same a previous program

If we run the above application we will get error because of lazy loading  the error is

Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into userdetails (userName, userId) values (?, ?)
Hibernate: insert into USER_ADDRESS (USER_ID, CITY_NAME, COUNTRY_NAME, DISTRICT_NAME, POSTAL_CODE, STREET_NAME) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into USER_ADDRESS (USER_ID, CITY_NAME, COUNTRY_NAME, DISTRICT_NAME, POSTAL_CODE, STREET_NAME) values (?, ?, ?, ?, ?, ?)
Hibernate: select userdetail0_.userId as userId0_0_, userdetail0_.userName as userName0_0_ from userdetails userdetail0_ where userdetail0_.userId=?
Exception in thread "main" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.hibernate.model.UserDetails.listOfAddresses, no session or session was closed
      at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
      at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
      at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:122)
      at org.hibernate.collection.PersistentBag.size(PersistentBag.java:248)
      at com.hibernate.UserAccess.main(UserAccess.java:43)


To rectify we have 2 options 
remove the session.close() 
         or
@ElementCollection(fetch=FetchType.EAGER)----->change this in UserDetails.java

Output:
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into userdetails (userName, userId) values (?, ?)
Hibernate: insert into USER_ADDRESS (USER_ID, CITY_NAME, COUNTRY_NAME, DISTRICT_NAME, POSTAL_CODE, STREET_NAME) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into USER_ADDRESS (USER_ID, CITY_NAME, COUNTRY_NAME, DISTRICT_NAME, POSTAL_CODE, STREET_NAME) values (?, ?, ?, ?, ?, ?)
Hibernate: select userdetail0_.userId as userId0_0_, userdetail0_.userName as userName0_0_, listofaddr1_.USER_ID as USER1_0_2_, listofaddr1_.CITY_NAME as CITY2_2_, listofaddr1_.COUNTRY_NAME as COUNTRY3_2_, listofaddr1_.DISTRICT_NAME as DISTRICT4_2_, listofaddr1_.POSTAL_CODE as POSTAL5_2_, listofaddr1_.STREET_NAME as STREET6_2_ from userdetails userdetail0_, USER_ADDRESS listofaddr1_ where userdetail0_.userId=listofaddr1_.USER_ID(+) and userdetail0_.userId=?
2







No comments:

Post a Comment