Saving Collections in Hibernate – @ElementCollection
In our previous examples we had seen how to embed one entity into another, how to change the column names using annotations.

In this example we are going to see how to save collections using Hibernate. For saving collections in database using hibernate, we are going to use the annotation @ElementCollection

Structure
structure

hibernate.cfg.xml

<hibernate-configuration>
  <session-factory>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernateannotation</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <property name="hibernate.show_sql">true</property>
    <mapping class="com.javainfinite.pojo.employee"/>
  </session-factory>
</hibernate-configuration>

NewHibernateUtil.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.javainfinite.pojo;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
public class NewHibernateUtil {

    private static final SessionFactory sessionFactory;
    
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

address.java

package com.javainfinite.pojo;

import javax.persistence.Embeddable;

@Embeddable
public class address {
    
    private String state;
    private String city;
    private String pincode;

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getCity() {
        return city;
    }

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

    public String getPincode() {
        return pincode;
    }

    public void setPincode(String pincode) {
        this.pincode = pincode;
    }
   
}

employee.java

package com.javainfinite.pojo;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.JoinTable;
import javax.persistence.ElementCollection;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table (name="Employee")
public class employee implements Serializable {
    
    @Id
    @GeneratedValue
    @Column(name="Employee_ID")
    private int eid;
    @Column(name="Employee_Name")
    private String ename;
    @Column(name="Employee_Password")
    private String epass;
    
    @Embedded
    @ElementCollection
    @JoinTable(name="Address-Collection")
    private List<address> address=new ArrayList();

    public List<address> getAddress() {
        return address;
    }

    public void setAddress(List<address> address) {
        this.address = address;
    }
    
    
    public int getEid() {
        return eid;
    }

    public void setEid(int eid) {
        this.eid = eid;
    }
    

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public String getEpass() {
        return epass;
    }

    public void setEpass(String epass) {
        this.epass = epass;
    }
    
}

We have used couple of new annotations here,
1. @ElementCollection – Used to indicate the hibernate that we are using another entity as collection
2. @JoinTable – This is optional, this is used to set the table name. If this is not mentioned, By default hibernate creates a table with name entityclass_collectionclass (Here – employee_address). Since we have mentioned the name as Address_Collection, table will be created on that name

Execution.java

package com.javainfinite.exec;

import com.javainfinite.pojo.NewHibernateUtil;
import com.javainfinite.pojo.address;
import com.javainfinite.pojo.employee;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Execution {
    
    public static void main(String args[])
    {
        Session session=NewHibernateUtil.getSessionFactory().openSession();
        try
        {
            Transaction transaction=session.beginTransaction();
            employee emp=new employee();
            
            address addr=new address();
            address addr1=new address();
            address addr2=new address();
           
            addr.setCity("Lightwells");
            addr.setState("Sandreas");
            addr.setPincode("088909");
            
            addr1.setCity("Merside");
            addr1.setState("Bermuda");
            addr1.setPincode("223212");
            
            addr2.setCity("Atlantis");
            addr2.setState("Hamnaputra");
            addr2.setPincode("233112");
            
            emp.setEname("Alpha");
            emp.setEpass("123456");
            emp.getAddress().add(addr);
            emp.getAddress().add(addr1);
            emp.getAddress().add(addr2);
            
            
            
            
            session.save(emp);
            
            transaction.commit();
            session.close();
            
        }
        catch(Exception e)
        {
            
        }
    }
}

Output:

op1

Here we can see hibernate creates 2 tables, Employee table and Address_Collection
Employee class has same data, the employee ID (Which we have mentioned as auto generated field), Employee_ Name and Employee_Password.

Address_Collection table takes the Employee_ID (Primary key of Employee table) as Foreign key and assigns the list of address for that ID.

Employee Table

op2

Address_Collection Table

op3

Here we can see that, Employee_ID (Primary key of Employee table) is considered as foreign key and corresponding address are saved in Address_Collection table

 

 

By Sri

Leave a Reply

Your email address will not be published. Required fields are marked *