Join is used to merge the columns, in the case of Hibernate we will create a relationship or mapping concept to perform the join operation:-
Type of relationship or association
One to Many --> One dept has multiple employees
Many to One ---> Multiple employees belonging from Single dept
Many to Many ---> Multiple Employee belonging from Multiple Dept.
One to One -------> One Dept to one Employee
Example of Join Syntax:-
Many to One ---> Multiple employees belonging from Single dept
Many to Many ---> Multiple Employee belonging from Multiple Dept.
One to One -------> One Dept to one Employee
Example of Join Syntax:-
Implement Many to one using Two Different Entity Class Dept and Employee:-
Code of Dept Class:-
package scs;
import java.util.Set;
import javax.persistence.*;
@Entity
@Table(name="tbl_dept")
public class Dept {
@Id
private int deptid;
@Column
private String deptname;
public int getDeptid() {
return deptid;
}
public void setDeptid(int deptid) {
this.deptid = deptid;
}
public String getDeptname() {
return deptname;
}
public void setDeptname(String deptname) {
this.deptname = deptname;
}
}
Code of Employee Class:-
package scs;
import javax.persistence.*;
@Entity
@Table(name="tbl_emp")
public class Employee {
@Id
private int empid;
@Column
private String empname;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="deptid",referencedColumnName="deptid")
private Dept dept;
public int getEmpid() {
return empid;
}
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
public void setEmpid(int empid) {
this.empid = empid;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
}
hiebernate.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="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/java5batch</property>
<property name="connection.username">root</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<mapping class="scs.Dept"></mapping>
<mapping class="scs.Employee"></mapping>
</session-factory>
</hibernate-configuration>
Code of ManytoOneExample.java:-
package scs;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
public class ManytoOneExample {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = new AnnotationConfiguration().configure().buildSessionFactory();
Session s = sf.openSession();
Dept d = new Dept();
d.setDeptid(20);
d.setDeptname("CS");
Employee em = new Employee();
em.setEmpid(1001);
em.setEmpname("SSS");
em.setDept(d);
Employee em1 = new Employee();
em1.setEmpid(1002);
em1.setEmpname("DDD");
em1.setDept(d);
Transaction tx = s.beginTransaction();
s.save(em);
s.save(em1);
tx.commit();
s.close();
sf.close();
}
}
Example to one to many :-
1) Create Dept.java Master class:-
package scs;
import java.util.Set;
import javax.persistence.*;
@Entity
@Table(name="tbl_dept")
public class Dept {
@Id
private int deptid;
@Column
private String deptname;
public Set getEmpref() {
return empref;
}
public void setEmpref(Set empref) {
this.empref = empref;
}
@OneToMany(fetch=FetchType.LAZY, targetEntity=Employee.class, cascade=CascadeType.ALL)
@JoinColumn(name = "deptid", referencedColumnName="deptid")
private Set empref;
public int getDeptid() {
return deptid;
}
public void setDeptid(int deptid) {
this.deptid = deptid;
}
public String getDeptname() {
return deptname;
}
public void setDeptname(String deptname) {
this.deptname = deptname;
}
}
2) Create Employee.Java Class as an Association Class
package scs;
import javax.persistence.*;
@Entity
@Table(name="tbl_emp")
public class Employee {
@Id
private int empid;
@Column
private String empname;
public int getEmpid() {
return empid;
}
public void setEmpid(int empid) {
this.empid = empid;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
}
3) Create 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="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/java5batch</property>
<property name="connection.username">root</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<mapping class="scs.Dept"></mapping>
<mapping class="scs.Employee"></mapping>
</session-factory>
</hibernate-configuration>
4) Create OnetoMany.java class:-
package scs;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
public class ManytoOneExample {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = new AnnotationConfiguration().configure().buildSessionFactory();
Session s = sf.openSession();
Dept d = new Dept();
d.setDeptid(10);
d.setDeptname("IT");
Employee em = new Employee();
em.setEmpid(1001);
em.setEmpname("XYZ");
Employee em1 = new Employee();
em1.setEmpid(1002);
em1.setEmpname("ABC");
Set st = new HashSet<>();
st.add(em);
st.add(em1);
d.setEmpref(st);
Transaction tx = s.beginTransaction();
s.save(d);
tx.commit();
s.close();
sf.close();
}
}
Now I am Explaining The Inner Join Example in Dept to Employee
package scs;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
public class JoinExample {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = new AnnotationConfiguration().configure().buildSessionFactory();
Session s = sf.openSession();
Query q = s.createQuery("select d.deptid,d.deptname,e.empid,e.empname from Dept d inner join d.empref e");
List lst = q.list();
Iterator it = lst.iterator();
while(it.hasNext())
{
Object arr[] = (Object[])it.next();
System.out.println(arr[0] + " "+ arr[1] + " "+arr[2] + " "+ arr[3]);
}
s.close();
sf.close();
}
}
Vendor
vid
vname
Set childern ----> store record of child object
Cutsomer
custid
custname
vid(fk) ----> it will take record which will be exist under master
Syntax of Left Join
select v.vname,v.vid,c.custid,c.custname from Vendor v left join v.children c.
Vendor information will match from Customer
Syntax of Right Join
select v.vname,v.vid,c.custid,c.custname from Vendor v right join v.children c.
Customer information will match from Vendor
Many to one :-
Pojo clas
Vendor:-
vid
vname
Customer
cid
cname
parentObjects
Right Join:-
select v.vname,v.vid,c.cname from Customer c Right Join c.parentObjects;
vendor table info will be matched from Customer Table
Left Join:-
select v.vname,v.vid,c.cname from Customer c Left Join c.parentObjects;
Customer Table info will be matched from Vendor Table
Inner Join:-
select v.vname,v.vid,c.cname from Customer c Inner Join c.parentObjects;
Customer Table Matched Information will be Show from Vendor name.
..................................................
Assignment:-
Project:-
ProjectId
ProjectName
ProjectDesc
...................................................................................................................................................
ProjectAssignment
Developerid
Developername
Projectid
One to many:-
Inner Join
Right Join
Left Join
many to one
Inner Join
Right Join
Left Join
Complete Sample example:-
package mappingser;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.*;
import org.hibernate.cfg.*;
import mapping.*;
/**
* Servlet implementation class ManyToOneSer
*/
@WebServlet("/ManyToOneSer")
public class ManyToOneSer extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ManyToOneSer() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Query q = session.createQuery("select v.vendroid,v.verndroname,c.customername from Customer c Inner Join c.parentObjects v");
List lst = q.list();
Iterator it = lst.iterator();
while(it.hasNext())
{
Object arr[] = (Object[]) it.next();
out.print(arr[0]+" "+arr[1]+" "+arr[2]+"<br>");
}
session.close();
out.println("One To Many is Done..!!");
factory.close();
}
}
Many To One Join Example:-
package uao;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class JoinMappingFile {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s =sf.openSession();
// Query q = s.createQuery("select v.vid,v.vname,c.customername from Customer c inner join c.parentObjects v");
// Query q = s.createQuery("select v.vid,v.vname,c.customername from Customer c left join c.parentObjects v");
Query q = s.createQuery("select v.vid,v.vname,c.customername from Customer c right join c.parentObjects v");
List lst = q.list();
Iterator it = lst.iterator();
while(it.hasNext())
{
Object arr[]= (Object[])it.next();
System.out.println(arr[0]+" "+arr[1]+" "+arr[2]);
}
s.close();
}
}
vid
vname
Set childern ----> store record of child object
Cutsomer
custid
custname
vid(fk) ----> it will take record which will be exist under master
Syntax of Left Join
select v.vname,v.vid,c.custid,c.custname from Vendor v left join v.children c.
Vendor information will match from Customer
Syntax of Right Join
select v.vname,v.vid,c.custid,c.custname from Vendor v right join v.children c.
Customer information will match from Vendor
Many to one :-
Pojo clas
Vendor:-
vid
vname
Customer
cid
cname
parentObjects
Right Join:-
select v.vname,v.vid,c.cname from Customer c Right Join c.parentObjects;
vendor table info will be matched from Customer Table
Left Join:-
select v.vname,v.vid,c.cname from Customer c Left Join c.parentObjects;
Customer Table info will be matched from Vendor Table
Inner Join:-
select v.vname,v.vid,c.cname from Customer c Inner Join c.parentObjects;
Customer Table Matched Information will be Show from Vendor name.
..................................................
Assignment:-
Project:-
ProjectId
ProjectName
ProjectDesc
...................................................................................................................................................
ProjectAssignment
Developerid
Developername
Projectid
One to many:-
Inner Join
Right Join
Left Join
many to one
Inner Join
Right Join
Left Join
Complete Sample example:-
package mappingser;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.*;
import org.hibernate.cfg.*;
import mapping.*;
/**
* Servlet implementation class ManyToOneSer
*/
@WebServlet("/ManyToOneSer")
public class ManyToOneSer extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ManyToOneSer() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Query q = session.createQuery("select v.vendroid,v.verndroname,c.customername from Customer c Inner Join c.parentObjects v");
List lst = q.list();
Iterator it = lst.iterator();
while(it.hasNext())
{
Object arr[] = (Object[]) it.next();
out.print(arr[0]+" "+arr[1]+" "+arr[2]+"<br>");
}
session.close();
out.println("One To Many is Done..!!");
factory.close();
}
}
Many To One Join Example:-
package uao;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class JoinMappingFile {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s =sf.openSession();
// Query q = s.createQuery("select v.vid,v.vname,c.customername from Customer c inner join c.parentObjects v");
// Query q = s.createQuery("select v.vid,v.vname,c.customername from Customer c left join c.parentObjects v");
Query q = s.createQuery("select v.vid,v.vname,c.customername from Customer c right join c.parentObjects v");
List lst = q.list();
Iterator it = lst.iterator();
while(it.hasNext())
{
Object arr[]= (Object[])it.next();
System.out.println(arr[0]+" "+arr[1]+" "+arr[2]);
}
s.close();
}
}
POST Answer of Questions and ASK to Doubt