Hibernate Many to Many Self Join using Annotations

In this section, you will learn how to do many to many self join using Annotations in Hibernate.

Ads

Tutorials   
How to write hello world example program in Hibernate? How to create one to one relationship in Hibernate 4 with Annotation? How to calculate minimum in Hibernate using the min() Function Hibernate 4.3.4 Released: Hibernate 4.3.4.Final Maven dependency Hibernate 4.3 Hello World: Example How to create SessionFactory in Hibernate 4.3.1? Hibernate 4 Hello World: Example of Hello World program Hibernate 4 create Session Factory: Example of creating Session Factory in Hibernate 4 Hibernate 4.3 and JPA 2.1 Example What is Hibernate in Java? Hibernate Overview and Architecture What is JPA 2.1? Hibernate 4.3.0.Final Maven dependency Hibernate 4.3 ORM Features Hibernate 4.3 Tutorial Hibernate Criteria average example Hibernate Criteria load all objects from table Hibernate Criteria Hibernate beginner tutorial Hibernate Session.delete() Example Hibernate save or update method example Hibernate Load Example Hibernate save Example - Rose India Hibernate 4 tutorials Hibernate Example Step by Step in Eclipse Hibernate Configuration files Setup Hibernate Environment Hibernate Architecture Hibernate Overview Hibernate 4.2 Tutorial Hibernate 4 Annotations Tutorial Hibernate 4 AnnotationSessionFactoryBean hibernate versions hibernate jndi hibernate tomcat hibernate metamodel generator hibernate entity Seam Hibernate C3P0 Hibernate hibernate shard hibernate means temporal hibernate jsf hibernate spring j2ee hibernate spring hibernate encrypted password alias_to_entity_map hibernate temporal jsf spring hibernate hibernate by example hibernate repository hibernate sample code
Ads

Hibernate Many to Many Self Join using Annotations

In this section, you will learn how to do many to many self join using Annotations in Hibernate.

In many to many self join table,  a table is related to itself using bridge table. In the below example,  faculty table has many to many relationship where every faculty is coworker and every coworker is faculty. The faculty table has self join many to many relationship using faculty_coworker

The project hierarchy is given below :

Database table query :

The query used to create a faculty table is given below :

CREATE TABLE `faculty` ( 
`faculty_id` bigint(10) NOT NULL auto_increment, 
`firstname` varchar(50) default NULL, 
`lastname` varchar(50) default NULL, 
PRIMARY KEY (`faculty_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 

The query used to create a faculty_coworker table is given below :

CREATE TABLE `faculty_coworker` ( 
`faculty_id` bigint(10) NOT NULL, 
`coworker_id` bigint(10) NOT NULL, 
PRIMARY KEY (`faculty_id`,`coworker_id`), 
KEY `FK_coworker` (`coworker_id`), 
CONSTRAINT `FK_coworker` FOREIGN KEY (`coworker_id`) REFERENCES `faculty` (`faculty_id`), 
CONSTRAINT `FK_faculty` FOREIGN KEY (`faculty_id`) REFERENCES `faculty` (`faculty_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 

hibernate.cfg.xml( /src/hibernate.cfg.xml )

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://192.168.10.13:3306/anky</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>

<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">validate</property>

<mapping class="net.roseindia.Faculty"/>
</session-factory>
</hibernate-configuration>

Faculty.java( /src/net/roseindia/Faculty.java )

package net.roseindia;

import java.util.*;
import javax.persistence.*;

@Entity
@Table(name="faculty")
public class Faculty {
@Id
@Column(name="faculty_id")
@GeneratedValue
private Long facultyId;

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

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

@ManyToMany(cascade={CascadeType.ALL})
@JoinTable(name="faculty_coworker",
[email protected](name="faculty_id")},
[email protected](name="coworker_id")})
private Set<Faculty> coworkers = new HashSet<Faculty>();

@ManyToMany(mappedBy="coworkers")
private Set<Faculty> colleagues = new HashSet<Faculty>();

/**
* @param firstname
* @param lastname
*/
public Faculty(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}

/**
* @return the facultyId
*/
public Long getFacultyId() {
return facultyId;
}

/**
* @param facultyId the facultyId to set
*/
public void setFacultyId(Long facultyId) {
this.facultyId = facultyId;
}

/**
* @return the firstname
*/
public String getFirstname() {
return firstname;
}

/**
* @param firstname the firstname to set
*/
public void setFirstname(String firstname) {
this.firstname = firstname;
}

/**
* @return the lastname
*/
public String getLastname() {
return lastname;
}

/**
* @param lastname the lastname to set
*/
public void setLastname(String lastname) {
this.lastname = lastname;
}

/**
* @return the coworkers
*/
public Set<Faculty> getCoworkers() {
return coworkers;
}

/**
* @param coworkers the coworkers to set
*/
public void setCoworkers(Set<Faculty> coworkers) {
this.coworkers = coworkers;
}

/**
* @return the colleagues
*/
public Set<Faculty> getColleagues() {
return colleagues;
}

/**
* @param colleagues the colleagues to set
*/
public void setColleagues(Set<Faculty> colleagues) {
this.colleagues = colleagues;
} 
}

ManageFaculty.java( /src/net/roseindia/ManageFaculty.java)

package net.roseindia;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class ManageFaculty {
private static SessionFactory sf;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args) {
try {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
sf = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}

System.out.println("********Hibernate Many to Many Self Join mapping using Annotations*******");
Session session = sf.openSession();
session.beginTransaction();

Faculty f1=new Faculty("Sachin","singh");
Faculty f2=new Faculty("Anirrudh","patel");
Faculty f3=new Faculty("Jane","patel");
Faculty f4=new Faculty("Rosini","Sharma");
Faculty f5=new Faculty("Rakesh","Chowdhary");

f1.getCoworkers().add(f2);
f1.getCoworkers().add(f3);
f2.getCoworkers().add(f1);
f2.getCoworkers().add(f3);
f3.getCoworkers().add(f1);
f3.getCoworkers().add(f2);
f4.getCoworkers().add(f5);
f5.getCoworkers().add(f4);

session.save(f1);
session.save(f2);
session.save(f3);
session.save(f4);
session.save(f5);

session.getTransaction().commit();
session.close();
}
}

OUTPUT

********Hibernate Many to Many Self Join mapping using Annotations*******
Hibernate: insert into faculty (firstname, lastname) values (?, ?)
Hibernate: insert into faculty (firstname, lastname) values (?, ?)
Hibernate: insert into faculty (firstname, lastname) values (?, ?)
Hibernate: insert into faculty (firstname, lastname) values (?, ?)
Hibernate: insert into faculty (firstname, lastname) values (?, ?)
Hibernate: insert into faculty_coworker (faculty_id, coworker_id) values (?, ?)
Hibernate: insert into faculty_coworker (faculty_id, coworker_id) values (?, ?)
Hibernate: insert into faculty_coworker (faculty_id, coworker_id) values (?, ?)
Hibernate: insert into faculty_coworker (faculty_id, coworker_id) values (?, ?)
Hibernate: insert into faculty_coworker (faculty_id, coworker_id) values (?, ?)
Hibernate: insert into faculty_coworker (faculty_id, coworker_id) values (?, ?)
Hibernate: insert into faculty_coworker (faculty_id, coworker_id) values (?, ?)
Hibernate: insert into faculty_coworker (faculty_id, coworker_id) values (?, ?)

You will get following record in the faculty table :

In the faculty_coworker table, you will get the following record :

Download Source Code

Advertisements

Ads
Share on Google+Share on Google+

Hibernate Many to Many Self Join using Annotations

Posted on: February 29, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: Hibernate Many to Many Self Join using Annotations  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads