Pages Navigation Menu

Coding is much easier than you think

Saving Collections in Hibernate

 

 
In our last Hibernate article, we learned about Embedding value object into an entity class. In this article we’re going to focus on saving a Collection in Hibernate.
 
Consider a scenario where the student have lots of address. So in this case we need to create more no of embedded object in the student class, which is so tedious at certain point. In such case we can use Collection to solve this problem. This collection can be a list, set, map, collection, sorted set, sorted map. Hibernate provides the facility to persist the collections object via @ElementCollection annotation.
 

Entity Class

 

package entity;

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.Id;
import javax.persistence.Table;

@Entity
@Table(name = "STUDENT")
public class Student {

	@Id
	@GeneratedValue
	@Column(name = "ID")
	private int id;

	@Column(name = "NAME")
	private String name;

	@Column(name = "DEPARTMENT")
	private String department;

	@Column(name = "COLLEGE")
	private String college;

	@ElementCollection
	private Collection
lisOfAddress = new ArrayList
(); // Create Getters and Setters }

 

@ElementCollection:

Defines a collection of instances of an embeddable class, this annotation must be specified if the collection is to be mapped by means of a collection table.
 

package entity;

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 = "STATE_NAME")
	private String state;
	@Column(name = "PIN_CODE")
	private String pincode;
        
        // Create Getters and Setters
}

 
hibernate.cfg.xml will be the same as in previous article.
 

HibernateTest class

 
Create the Main class to run the example.

package util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import entity.Address;
import entity.Student;

public class HibernateUtil {

	public static void main(String[] args) {

		Configuration cf = new Configuration().configure("hibernate.cfg.xml");

		StandardServiceRegistryBuilder srb =
                               new StandardServiceRegistryBuilder();
		srb.applySettings(cf.getProperties());
		ServiceRegistry sr = srb.build();
		SessionFactory sf = cf.buildSessionFactory(sr);

		Session session = sf.openSession();
		Transaction tx = session.beginTransaction();
		
		Address address1 = new Address();
		address1.setStreet("Race cource");
		address1.setCity("Coimbatore");
		address1.setState("Tamilnadu");
		address1.setPincode("642001");
		
		Address address2 = new Address();
		address2.setStreet("Besant nagar");
		address2.setCity("Chennai");
		address2.setState("Tamilnadu");
		address2.setPincode("600001");
		
		Student student = new Student();

		student.setName("Lahir Nisha");
		student.setDepartment("ECE");
		student.setCollege("SKCET");
		
		//adding addresses object to the list of address
		student.getLisOfAddress().add(address1);
		student.getLisOfAddress().add(address2);

                session.save(student);
        
		tx.commit();
		session.close();
		sf.close();
	}
}

 

Rut it – Eclipse Console

 

 
When you run the above program two tables are created in database, first table is for Student entity “STUDENT” and second table is for the embeddable object (Address) – “Student_lisOfAddress” (The default table name for this table gets generated based on – Entity class name_Name of the embeddable object in the entity class).
 
Here the ‘Student_ID’ column in ‘Student_lisOfAddress’ is the foreign key reference of Student tables ‘ID’. In next article we shall learn to override the default collection class table name and to add primary key to it.
 
download

One Comment

  1. Why we are adding addresses object to the list of address using getLisOfAddress() instead of setLisOfAddress()