Example of @ElementCollection in Hibernate Annotation

By Arvind Rai, January 27, 2013
In Hibernate Annotation, @ElementCollection is the feature which gets the columns values from another table without mapping two tables. We have taken two entity student and college. In college entity, we will fetch students without mapping student and college entity. @CollectionTable will join the two tables for the given primary and foreign key.
Student.java
package com.concretepage.persistence;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="student")
public class Student implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	@Column(name="student_id")
	private int studentId;
	
	@Column(name="student_name")
	private String studentName;
	
	@Column(name="college_id")
	private int collegeId;

	public Student(int studentId,String studentName,int collegeId){
		this.studentId=studentId;
		this.studentName=studentName;
		this.collegeId=collegeId;
	}

	public int getStudentId() {
		return studentId;
	}

	public void setStudentId(int studentId) {
		this.studentId = studentId;
	}

	public String getStudentName() {
		return studentName;
	}

	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}
	
	public int getCollegeId() {
		return collegeId;
	}

	public void setCollegeId(int collegeId) {
		this.collegeId = collegeId;
	}

}
 
College.java
package com.concretepage.persistence;

import java.io.Serializable;
import java.util.Set;

import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Table;

@Entity
@Table(name="college")
public class College implements Serializable {
	private static final long serialVersionUID = 1L;
	@Id
	@Column(name="college_id")
    private int collegeId;	
	
	@Column(name="name")
	private String collegeName;
	
	@ElementCollection
	@CollectionTable(name="student", joinColumns=@JoinColumn(name="college_id"))
	@Column(name="student_name")
	private Set<String> students;
	 
	public College(int collegeId,String collegeName){
		this.collegeId=collegeId;
		this.collegeName=collegeName;
	}
	
	public Set<String> getStudents() {
		return students;
	}

	public void setStudents(Set<String> students) {
		this.students = students;
	}

	public int getCollegeId() {
		return collegeId;
	}

	public void setCollegeId(int collegeId) {
		this.collegeId = collegeId;
	}

	public String getCollegeName() {
		return collegeName;
	}

	public void setCollegeName(String collegeName) {
		this.collegeName = collegeName;
	}
}
 
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.url">
    jdbc:mysql://localhost:3306/hibernate</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password"></property>
    <property name="hibernate.connection.pool_size">10</property>
    <property name="show_sql">true</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <mapping class="com.concretepage.persistence.Student"/>
    <mapping class="com.concretepage.persistence.College"/>

  </session-factory>
</hibernate-configuration>
 
HibernateUtil.java
package com.concretepage.util;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import com.concretepage.persistence.College;
import com.concretepage.persistence.Student;

public class HibernateUtil {
	private static final SessionFactory concreteSessionFactory;
	    static {
	        try {
	            concreteSessionFactory = new AnnotationConfiguration()
	                    .configure().buildSessionFactory();
	        } catch (Throwable ex) {
	            throw new ExceptionInInitializerError(ex);
	        }
	    }
	    public static Session getSession()
	            throws HibernateException {
	        return concreteSessionFactory.openSession();
	    }
	    
	    public static void main(String... args){
	    	Session session=getSession();
	    	session.beginTransaction();
	    	
	    	College c=new College(1,"S.S.P.C");
	    	session.persist(c);
	        Student s1=new Student(1,"Atul",1);
	        session.persist(s1);
	        Student s2=new Student(2,"Saurabh",1);
	        session.persist(s2);
	    		    	
	       	session.getTransaction().commit();
	       	session.refresh(c);
	       	College ob=(College)session.get(College.class, new Integer(1));
	       	Set<String> names=ob.getStudents();
	       	for(String s:names){
	       		System.out.println(s);	
	       	}
	    }
	}
 
Output
Hibernate: insert into college (name, college_id) values (?, ?)
Hibernate: insert into student (college_id, student_name, student_id) values (?, ?, ?)
Hibernate: insert into student (college_id, student_name, student_id) values (?, ?, ?)
Hibernate: select college0_.college_id as college1_1_0_, college0_.name as name1_0_ from college college0_ where college0_.college_id=?
Hibernate: select students0_.college_id as college2_1_0_, students0_.student_name as student3_0_ from student students0_ where students0_.college_id=?
Saurabh
Atul
 
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us