Hibernate One to Many Self Join using Annotations

In this section, you will learn one 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 One to Many Self Join using Annotations

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

In self join, the table is mapped to itself. Means two field of a table is involved in this mapping. For example in the below figure, contractor_id and labour_id have one to many relationship. The relationship is as follows : many labors are headed by a contractor. But contractor is also one of the labour(senior labour). That's why it is mentioned in labour table.

EXAMPLE

The project hierarchy is given below :

Database table query :

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

CREATE TABLE `labour` ( 
`labour_id` bigint(10) NOT NULL auto_increment, 
`firstname` varchar(40) default NULL, 
`lastname` varchar(40) default NULL, 
`contractor_id` bigint(10) default NULL, 
PRIMARY KEY (`labour_id`), 
KEY `labour_id` (`labour_id`), 
KEY `FK_labour` (`contractor_id`), 
CONSTRAINT `FK_labour` FOREIGN KEY (`contractor_id`) REFERENCES `labour` (`labour_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 

CODE

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.Labour" />

</session-factory>
</hibernate-configuration>

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

package net.roseindia;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "labour")
public class Labour {
@Id
@Column(name = "labour_id")
@GeneratedValue
private Long labourId;

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

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

@ManyToOne(cascade = { CascadeType.ALL })
@JoinColumn(name = "contractor_id")
private Labour contractor;

@OneToMany(mappedBy = "contractor")
private Set<Labour> subordinates = new HashSet<Labour>();

public Labour(String firstname, String lastname) {
super();
this.firstname = firstname;
this.lastname = lastname;
}

public Long getLabourId() {
return labourId;
}

public void setLabourId(Long labourId) {
this.labourId = labourId;
}

public String getFirstname() {
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

public Labour getContractor() {
return contractor;
}

public void setContractor(Labour contractor) {
this.contractor = contractor;
}

public Set<Labour> getSubordinates() {
return subordinates;
}

public void setSubordinates(Set<Labour> subordinates) {
this.subordinates = subordinates;
}
}

ManageLabour.java( /src/net/roseindia/ManageLabour.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 ManageLabour {
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 One to many Self Join Example**********");
Session session = sf.openSession();
session.beginTransaction();

Labour contractor = new Labour("Abay", "Singh");

Labour labour1 = new Labour("Shambhu", "Dayal");
Labour labour2 = new Labour("Ram", "Narayan");

labour1.setContractor(contractor);
labour2.setContractor(contractor);

session.save(labour1);
session.save(labour2);

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

OUTPUT

After executing ManageLabour class, you will get the following output in console :

**********Hibernate One to many Self Join Example**********
Hibernate: insert into labour (contractor_id, firstname, lastname) values (?, ?, ?)
Hibernate: insert into labour (contractor_id, firstname, lastname) values (?, ?, ?)
Hibernate: insert into labour (contractor_id, firstname, lastname) values (?, ?, ?)

In labour table, you will get the following records :

Download Source Codes

Advertisements

Ads
Share on Google+Share on Google+

Hibernate One to Many Self Join using Annotations

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

Advertisements

Ads
 

Discuss: Hibernate One to Many Self Join using Annotations  

Post your Comment


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

Ads

 

Ads