Home  >  Hibernate

Example of @SecondaryTables in Hibernate Annotation

By Arvind Rai, January 28, 2013
@SecondaryTables is the annotation in hibernate by which an entity can map more than one table to fetch the data. The entity which is fetching data should have @SecondaryTables annotations. It associates secondary table on the basis of primary and foreign key and also on the basis of unique constrains.
In the example I have taken two entity one is student and another is name. Student entity will fetch secondary entity name on the basis of primary key.

Name.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="name")
public class Name implements Serializable{
	private static final long serialVersionUID = 1L;
	@Id
	@Column(name="id")
	private int id;
	@Column(name="name")
	private String name;
	public Name(int id,String name){
		this.id=id;
		this.name=name;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
} 
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.PrimaryKeyJoinColumn;
import javax.persistence.SecondaryTable;
import javax.persistence.SecondaryTables;
import javax.persistence.Table;
@Entity
@Table(name="student")
@SecondaryTables({
    @SecondaryTable(name="name", pkJoinColumns={
        @PrimaryKeyJoinColumn(name="id", referencedColumnName="student_id") })
})
public class Student implements Serializable {
	private static final long serialVersionUID = 1L;
	@Id
	@Column(name="student_id")
	private int studentId;
	@Column(table="name")
	private String name;
	public Student(int studentId){
		this.studentId=studentId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getStudentId() {
		return studentId;
	}
	public void setStudentId(int studentId) {
		this.studentId = studentId;
	}
}
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.Name"/>
    <mapping class="com.concretepage.persistence.Student"/>
  </session-factory>
</hibernate-configuration>
HibernateUtil.java
package com.concretepage.util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import com.concretepage.persistence.Name;
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();
		Student s= new Student(1);
	    	session.persist(s);
	        Name n=new Name(1,"Ankita");
                session.persist(n);
	        session.getTransaction().commit();
	       	session.refresh(s);
	       	session.refresh(n);
	       	Student ob=(Student)session.get(Student.class, new Integer(1));
	       	String name=ob.getName();
	       	System.out.println(name);
	    }
} 
Output
Hibernate: insert into name (name, id) values (?, ?)
Hibernate: insert into student (student_id) values (?)
Hibernate: select student0_.student_id as student1_1_0_, student0_1_.name as name0_0_ from student student0_ left outer join name student0_1_ on student0_.student_id=student0_1_.id where student0_.student_id=?
Hibernate: select name0_.id as id0_0_, name0_.name as name0_0_ from name name0_ where name0_.id=?
Ankita
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS








Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us