Now we’ll learn about the Saving Collections in Hibernate with Example.

In the previous tutorial, we learned about Embedding value type object.

Now what will be doing when there are a lot of embeddable objects instead of the single embeddable objects, In previous we have used two embeddable objects in the UserDetails class.
Suppose we want to keep tracks all addresses of a user, so think about one minute how to get.

Lets we will use the Collection for that.

1. In this code snip, User has one address

class UserDetails{
    —–
    private int userId;
    —–
    private Address address;
    —–
}

2. In this code snip User has two addresses

class UserDetails{
    —–
    private int userId;
    —–
    private Address address1;
    private Address address2;
    —–

}

3. In this code snip User has more than two addresses

class UserDetails{
    —–
    private int userId;
    —–
    private Address address1;
    private Address address2;
    —–
    private Address addressN;
    —–
}

In the third case how to manage the records about addresses for that user, now for managing this type of problems we have to use the collection, we do not need to care about how many of the addresses user has. Let’s see there is the same change in the code for that…

class UserDetails{
    —–
    private int userId;
    —–
    private List<Address> addresses = new ArrayList<Address>();
    —–
}
Hibernate provides the facility to persist the collections. A collection can be a list, set, map, collection, sorted set, sorted map. java.util.List, java.util.Set, java.util.Collection, java.util.SortedSet, java.util.SortedMap etc. are the real interface types to declared the persistent collection-valued fields. Hibernate injects persistent collections based on the type of interface. The collection instances usually behave likes the types of value behaviour. Instances of collections are auto persisted if a persistent object refers it and are deleted automatically if it is not referred through. Elements of collection may shift from one table to another when a persistent object passed the collection to another persistent object.

We look following example of Object of Entity Type: 

@Entity
@Table(name=”TBL_USER_DETAILS“)

public class UserDetails{
@Id

     @Column(name=”USER_ID”, type=”INTEGER”)
     @GeneratedValue(strategy=GenerationType.AUTO)

private long userId;
@Column(name=”USER_NAME”, type=”String”)
private String userName;
@ElementCollection
private Collection<Address> lisOfAddresses = new ArrayList<Address>();
public Collection<Address> getLisOfAddresses() {
return lisOfAddresses;
}
public void setLisOfAddresses(Collection<Address> lisOfAddresses) {
this.lisOfAddresses = lisOfAddresses;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String toString()
{
return “[User Name: “+userName+”n Office Address: “+lisOfAddresses+”]”;
}
}

@ElementCollection:
Target:
Fields (including property get methods)Defines a collection of instances of a basic type or embeddable class. Must be specified if the collection is to be mapped by means of a collection table.
Address.java

package com.sdnext.hibernate.tutorial.dto;

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

@Embeddable //for value object it is not is an entity object. Value object means does not have real meaning for self individually.
public class Address
{
@Column(name=”STREET_NAME”)
private String street;
@Column(name=”CITY_NAME”)
private String city;
 @Column(name=”STATE_NAME”)
private String state;
@Column(name=”PIN_CODE”)
private String pincode;

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 getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String toString()
{
return ” {Street: “+street+” City: “+city+” State: “+state+” Pincode: “+pincode+” }”;
}
}

hibernate.cfg.xml will be the same as the previous chapter.


HibernateTestDemo.java

package com.sdnext.hibernate.tutorial;

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

import com.sdnext.hibernate.tutorial.dto.Address;
import com.sdnext.hibernate.tutorial.dto.UserDetails;

public class HibernateTestDemo {

/**
* @param args
*/
public static void main(String[] args)
{
UserDetails user = new UserDetails();//Create user object
user.setUserName(“Dinesh Rajput”); //Set user name

Address address1 = new Address(); // create first embedded object address
address1.setStreet(“First Street”);
address1.setCity(“First City”);
address1.setState(“First State”);
address1.setPincode(“First Pin”);

Address address2 = new Address(); // create second embedded object address
address2.setStreet(“Second Street”);
address2.setCity(“Second City”);
address2.setState(“Second State”);
address2.setPincode(“Second Pin”);
//adding addresses object to the list of address
user.getLisOfAddresses().add(address1);
user.getLisOfAddresses().add(address2);

SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); //create session factory object
Session session = sessionFactory.openSession(); //create session object from the session factory
session.beginTransaction(); //initialize the transaction object from session
session.save(user); // save the user
session.getTransaction().commit(); //commit the transaction
session.close(); //closing session
}
}

Output:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into TBL_USER_DETAILS (USER_NAME) values (?)
Hibernate: insert into TBL_USER_DETAILS_lisOfAddresses (TBL_USER_DETAILS_USER_ID, CITY_NAME, PIN_CODE, STATE_NAME, STREET_NAME) values (?, ?, ?, ?, ?)
Hibernate: insert into TBL_USER_DETAILS_lisOfAddresses (TBL_USER_DETAILS_USER_ID, CITY_NAME, PIN_CODE, STATE_NAME, STREET_NAME) values (?, ?, ?, ?, ?)

Saving Collections in Hibernate with Example
Look carefully to the output line, there are two tables here in the database, first for the UserDetails entity “TBL_USER_DETAILS” and second for the embeddable object Address name is “TBL_USER_DETAILS_lisOfAddresses ” (this is default name of table for address Entity Table Name_field name of the list of the embeddable object in the entity class).
Here see that there is one table for the address object created separately for the collection.
1. First Table TBL_USER_DETAILS
Saving Collections in Hibernate
 2. Second Table TBL_USER_DETAILS_lisOfAddresses 
Saving Collections in Hibernate with Example Tables

In the second table first column, TBL_USERS_DETAILS_USER_ID has the user id is foreign key for this table and primary key of the  TBL_USER_DETAILS table.

Saving Collections in Hibernate table output


In Next Chapter, you will learn more about the configuration of the collection and adding keys.

<<Previous Chapter 13<<    >>Next Chapter15