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







generator in hibernate with annotations

//In this program i use increment generator if you to know about the other generators just change the name and try it 

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.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Table;

import org.hibernate.annotations.CollectionId;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;

@Entity
@Table(name = "userdetails")
public class UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer userId;
private String userName;
@ElementCollection
@JoinTable(name="USER_ADDRESS",joinColumns=@JoinColumn(name="USER_ID"))
@GenericGenerator(name="increment-generator",strategy="increment")
@CollectionId(columns = { @Column(name="ADDRESS_ID") }, generator = "increment-generator", type = @Type(type="long"))
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();
factory.close();
}

}



hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">system</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.OracleDialect</property>


<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping class="com.hibernate.model.UserDetails" />


</session-factory>

</hibernate-configuration>

Using collection type set in hibernate with annotations



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.HashSet;
import java.util.Set;

import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "userdetails")
public class UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer userId;
private String userName;
@ElementCollection
private Set<Address> listOfAddresses = new HashSet<Address>();

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

public void setListOfAddresses(Set<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();
factory.close();
}

}


hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">system</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.OracleDialect</property>


<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping class="com.hibernate.model.UserDetails" />


</session-factory>

</hibernate-configuration>