How to use Foreign Key in Java with using of Hibernate?

1.First open XAMPP Control panel and start MySQL port 3306.

XAMPP Control panel

Open the SQLyog for create database.

SQLyog provides all the tools you need to manage and navigate databases. Note that to start working with databases in SQLyog you need to connect to a MySQL server.

Connect to Mysql host

Create database new tab.

After that we have creating table registration and roll.

creating table registration
creating table registration

2. Open the eclipse ide and create new dynamic web project which name ForeignKey.

Create 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>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/newtab</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <mapping resource="pojo/Registration.hbm.xml"/>
  <mapping resource="pojo/Roll.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

Create hibernate.revenge.xml.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD
 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd" >

<hibernate-reverse-engineering>
  <table-filter match-catalog="newtab" match-name="registration"/>
  <table-filter match-catalog="newtab" match-name="roll"/>
</hibernate-reverse-engineering>

• Create pojo for Registration and Roll with Registration.hbm.xml and Roll.hbm.xml file.

Registration .java

package pojo;
public class Registration  implements java.io.Serializable {
	private static final long serialVersionUID = 1L;
	private Integer id;
     private Roll roll;
     private String name;
     private String email;
     private String password;
  public Registration() {
    }
   public Registration(Roll roll, String name, String email, String password) {
       this.roll = roll;
       this.name = name;
       this.email = email;
       this.password = password;
    }
    public Integer getId() {
        return this.id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }                                                                             
    public Roll getRoll() {
        return this.roll;
    }                                                                  
    
    public void setRoll(Roll roll) {
        this.roll = roll;
    }
    public String getName() {
        return this.name;
    }
      public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return this.email;
    }
       public void setEmail(String email) {
        this.email = email;
    }
    public String getPassword() {
        return this.password;
    }
      public void setPassword(String password) {
        this.password = password;
    }
}

Roll.java

package pojo;
import java.util.HashSet;
import java.util.Set;

public class Roll  implements java.io.Serializable {
    private Integer rollid;
     private String rollname;
     private Set registrations = new HashSet(0);
    public Roll() {
    }
    public Roll(String rollname, Set registrations) {
       this.rollname = rollname;                                                  
       this.registrations = registrations;                                     
    }
    public Integer getRollid() {                                                     
        return this.rollid;                                                   
    }                                                                        
    public void setRollid(Integer rollid) {                                          
        this.rollid = rollid;                                              
    }
    public String getRollname() {
        return this.rollname;
    }   
    public void setRollname(String rollname) {
        this.rollname = rollname;
    }
    public Set getRegistrations() {
        return this.registrations;
    }  
    public void setRegistrations(Set registrations) {
        this.registrations = registrations;
    }
}

Registration.hbm.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Generated Jun 16, 2017 12:06:36 PM by Hibernate Tools 5.2.3.Final --><!DOCTYPE hibernate-mapping
 PUBLIC "-//Hibernate/Hibernate
 Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping auto-import="true" default-access="property" default-cascade="none" default-lazy="true">
    <class catalog="newtab" dynamic-insert="false" dynamic-update="false" mutable="true" name="pojo.Registration" 
    optimistic-lock="version" polymorphism="implicit" select-before-update="false" table="registration">
        <id name="id" type="java.lang.Integer">
            <column name="id"/>
            <generator class="identity"/>
        </id>
        <many-to-one class="pojo.Roll" embed-xml="true" fetch="select" insert="true" name="roll" not-found="exception" 
        optimistic-lock="true" unique="false" update="true">
            <column name="rollid"/>
        </many-to-one>
        <property generated="never" lazy="false" name="name" optimistic-lock="true" type="string" unique="false">
            <column length="45" name="name"/>
        </property>
        <property generated="never" lazy="false" name="email" optimistic-lock="true" type="string" unique="false">
            <column length="45" name="email"/>
        </property>
        <property generated="never" lazy="false" name="password" optimistic-lock="true" type="string" unique="false">
            <column length="45" name="password"/>
        </property>
    </class>
</hibernate-mapping>

Roll.hbm.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Generated Jun 16, 2017 12:06:36 PM by Hibernate Tools 5.2.3.Final --><!DOCTYPE hibernate-mapping 
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping auto-import="true" default-access="property" default-cascade="none" default-lazy="true">
    <class catalog="newtab" dynamic-insert="false" dynamic-update="false" mutable="true" name="pojo.Roll" optimistic-lock="version" 
    polymorphism="implicit" select-before-update="false" table="roll">
        <id name="rollid" type="java.lang.Integer">
            <column name="rollid"/>
            <generator class="identity"/>
        </id>
        <property generated="never" lazy="false" name="rollname" optimistic-lock="true" type="string" unique="false">
            <column length="45" name="rollname"/>
        </property>
        <set embed-xml="true" fetch="select" inverse="true" lazy="true" mutable="true" name="registrations" optimistic-lock="true"
         sort="unsorted" table="registration">
            <key on-delete="noaction">
                <column name="rollid"/>
            </key>
            <one-to-many class="pojo.Registration" embed-xml="true" not-found="exception"/>
        </set>
    </class>
</hibernate-mapping>

Create Hibernate Util File.

Util.java

package HiberUtil;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Util {
	public static final SessionFactory SESSION_FACTORY;
	static
	{
		try
		{
			SESSION_FACTORY=new Configuration().configure().buildSessionFactory();
		}
		catch (Throwable ex) {
	
			System.err.println("sesstion fectory creatial faild.." +ex);
			throw new ExceptionInInitializerError();
		}
	}
	public static SessionFactory getSessionfactory()
	{
		return SESSION_FACTORY;
	}
}

Create Blmanager(Business Logic File)

BLManager.java

package BLManager;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import pojo.Registration;
import pojo.Roll;

public class BLManager {
	
	SessionFactory sf=HiberUtil.Util.getSessionfactory();
	Session s=sf.openSession();
	Transaction tr=s.beginTransaction();
	public Roll checkroll(String rolln) {                                     
		// TODO Auto-generated method stub
		Criteria cr=s.createCriteria(Roll.class);
		cr.add(Restrictions.eq("rollname", rolln));
		Roll rr=(Roll) cr.uniqueResult();
		return rr;                                                     
	}                                                                   
	public void insertdemo(Registration rs) {                                
		// TODO Auto-generated method stub
		s.save(rs);
		tr.commit();	
	}
	
}

Create Jsp File.

Index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="DemoNew"  method="post">
<table>
	<tr>
		<td>Name:</td>
		<td><input type="text" name="name"></td>
	</tr>
	<tr>
		<td>Email:</td>                                                                                    
		<td><input type="text" name="email"></td>                           
	</tr>                                                                                                                                
	<tr>
		<td>Roll:</td>
		<td><select name="roll">
		<option value="Admin">Admin</option>
		<option value="Student">Student</option>
		<option value="HR">HR</option>
		</select>
	</tr>
	<tr>
		<td><input type="submit" value="Insert"></td>
	</tr>
</table>
</form>
</body>
</html>

Create Servlet File.

DemoNew.java

package Controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.SecureRandom;
import java.util.Random;

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 BLManager.BLManager;
import pojo.Registration;
import pojo.Roll;
@WebServlet("/DemoNew")
public class DemoNew extends HttpServlet {
	private static final long serialVersionUID = 1L;
	 private static final Random RANDOM = new SecureRandom();
	  public static final int PASSWORD_LENGTH = 8;
   public DemoNew() {
        super();
        // TODO Auto-generated constructor stub                                                          
    }                                                                                                                             
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//doGet(request, response);
		PrintWriter out=response.getWriter();
		String name=request.getParameter("name");
		String email=request.getParameter("email");
		String password=request.getParameter("password");	
		String rolln=request.getParameter("roll");
		BLManager bl=new BLManager();
		Roll ro=new Roll();
		//String pw=DemoNew.generateRandomPassword();
		Registration rs=new Registration();
		ro=bl.checkroll(rolln);
		rs.setName(name);
		rs.setEmail(email);
		rs.setPassword(password);
	    //rs.setPassword(pw);
		rs.setRoll(ro);
		bl.insertdemo(rs);
		out.println("<h2>Record Inserted</h2>");
	}

}

Entire Structure will be generating in Eclipse Like below.

Structure generating in Eclipse

Run the Application on Tomcat Server.

Run the Application on Tomcat Server

After than Fill the data into that.

Data Fill

You will see the Output as mentioned below

Output

We have checking the database for inserted data.

checking the database

Post Comment

Your email address will not be published. Required fields are marked *

Please type your comment