التخطي إلى المحتوى الرئيسي

Join in Hibernate Example, Hibernate Relationship using One to Many and Many to one


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:-
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();
}
}

تعليقات

المشاركات الشائعة من هذه المدونة

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

JDBC using JSP and Servlet

JDBC means Java Database Connectivity ,It is intermediates from Application to database. JDBC has different type of divers and provides to communicate from database server. JDBC contain four different type of approach to communicate with Database Type 1:- JDBC-ODBC Driver Type2:- JDBC Vendor specific Type3 :- JDBC Network Specific Type4:- JDBC Client-Server based Driver  or JAVA thin driver:- Mostly we prefer Type 4 type of Driver to communicate with database server. Step for JDBC:- 1  Create Database using MYSQL ,ORACLE ,MS-SQL or any other database 2   Create Table using database server 3   Create Form according to database table 4  Submit Form and get form data into servlet 5  write JDBC Code:-     5.1)   import package    import java.sql.*     5.2)  Add JDBC Driver according to database ide tools     5.3)  call driver in program         ...