• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Hibernate One To One Mapping XML Example with Foreign Key

November 10, 2016 by javainterviewpoint Leave a Comment

In the previous article, we have learnt about Hibernate One To One Mapping With Primary Key. In this Hibernate One To One Mapping with Foreign Key.

Creating table

Create EMPLOYEE and DEPARTMENT Tables, simply Copy and Paste the following SQL query in the query editor to get the table created.

CREATE TABLE "EMPLOYEE" 
 ( "EMP_ID" NUMBER(10,0) NOT NULL ENABLE, 
 "NAME" VARCHAR2(255 CHAR), 
 "AGE" NUMBER(10,0), 
 PRIMARY KEY ("EMP_ID")
 );
 
CREATE TABLE "DEPARTMENT" 
 ( "DEP_ID" NUMBER(10,0) NOT NULL ENABLE, 
 "EMP_ID" NUMBER(10,0) NOT NULL ENABLE, 
 "DEP_NAME" VARCHAR2(255 CHAR), 
 "DESIGNATION" VARCHAR2(255 CHAR), 
 PRIMARY KEY ("DEP_ID"),
 CONSTRAINT fk_emp FOREIGN KEY("EMP_ID") REFERENCES EMPLOYEE("EMP_ID")
 );

Folder Structure:

Hibernate One To One Mapping Foreign Key

  1. Create a simple Maven Project “HibernateTutorial” and create a package for our source files “com.javainterviewpoint” under  src/main/java 
  2. Now add the following dependency in the POM.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0	http://maven.apache.org/xsd/maven-4.0.0.xsd">
       <modelVersion>4.0.0</modelVersion>
       <groupId>HibernateTutorial</groupId>
       <artifactId>HibernateTutorial</artifactId>
       <version>0.0.1-SNAPSHOT</version>
       <properties>
          <hibernate.version>4.3.11.Final</hibernate.version>
          <oracle.connector.version>11.2.0</oracle.connector.version>
       </properties>
    
       <dependencies>
         <!-- Hibernate -->
         <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
         </dependency>
    
         <!-- Oracle -->
         <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc14</artifactId>
            <version>${oracle.connector.version}</version>
         </dependency>
       </dependencies>
       <build>
         <sourceDirectory>src</sourceDirectory>
         <plugins>
           <plugin>
             <artifactId>maven-compiler-plugin</artifactId>
             <version>3.3</version>
             <configuration>
             <source>1.7</source>
             <target>1.7</target>
             </configuration>
           </plugin>
         </plugins>
       </build>
     </project>
  3. Create the Java classes Employee.java, Department.java, EmployeeHibernateOneToOne.java   and RetrieveEmployee.java under  com.javainterviewpoint folder.
  4. Place the employee.hbm.xml, department.hbm.xml, hibernate.cfg.xml under the src/main/resources  directory

Hibernate One To One Mapping Example

Employee.java

Create a new Java file Employee.java under the package com.javainterviewpoint and add the following code

package com.javainterviewpoint;

import java.io.Serializable;

public class Employee implements Serializable 
{
    private static final long serialVersionUID = -889976693182180703L;
    
    private int emp_id;
    private String name;
    private int age;
    public Employee()
    {
        super();
    }
    public Employee(int emp_id, String name, int age)
    {
        super();
        this.emp_id = emp_id;
        this.name = name;
        this.age = age;
    }
    public int getEmp_id()
    {
        return emp_id;
    }
    public void setEmp_id(int emp_id)
    {
        this.emp_id = emp_id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public int getAge()
    {
        return age;
    }
    public void setAge(int age)
    {
        this.age = age;
    }
    @Override
    public String toString()
    {
        return "Employee [emp_id=" + emp_id + ", name=" + name + ", age=" + age + "]";
    }
}

Our Employee class is a simple POJO class consisting of the getters and setters for the Employee class properties (emp_id, name, age).

Department.java

Create a new Java file Department.java under the package com.javainterviewpoint and add the following code

package com.javainterviewpoint;

import java.io.Serializable;

public class Department implements Serializable 
{
    private int dep_id;
    private String dep_name;
    private String designation;
    
    private Employee employee;

    public Department()
    {
        super();
    }

    public Department(int dep_id, String dep_name, String designation, Employee employee)
    {
        super();
        this.dep_id = dep_id;
        this.dep_name = dep_name;
        this.designation = designation;
        this.employee = employee;
    }

    public int getDep_id()
    {
        return dep_id;
    }

    public void setDep_id(int dep_id)
    {
        this.dep_id = dep_id;
    }

    public String getDep_name()
    {
        return dep_name;
    }

    public void setDep_name(String dep_name)
    {
        this.dep_name = dep_name;
    }

    public String getDesignation()
    {
        return designation;
    }

    public void setDesignation(String designation)
    {
        this.designation = designation;
    }

    public Employee getEmployee()
    {
        return employee;
    }

    public void setEmployee(Employee employee)
    {
        this.employee = employee;
    }

    @Override
    public String toString()
    {
        return "Department [dep_id=" + dep_id + ", dep_name=" + dep_name + ", designation=" + designation
                + ", employee=" + employee + "]";
    }
}

Other interesting articles which you may like …

  • Hibernate Hello World Example in Eclipse (XML Mapping)
  • Hibernate Hello World Example in Eclipse (Annotation)
  • Hibernate One To Many Mapping XML Example
  • Hibernate Many To Many Mapping Example – XML Mapping
  • Hibernate One To One Bidirectional Mapping – Primary Key(Annotation)
  • Hibernate One To Many Mapping Example Using Annotation
  • Hibernate Many To Many Mapping Example – Annotation
  • Hibernate CRUD Example in Eclipse (XML Mapping) with Maven + Oracle
  • Hibernate Inheritance – Table Per Class Hierarchy (XML Mapping & Annotation)
  • Hibernate Inheritance – Table Per Subclass Hierarchy (XML Mapping & Annotation)
  • Hibernate Inheritance – Table Per Concrete Class Hierarchy Example(XML Mapping & Annotation)
  • Hibernate Composite Primary Key Tutorial – Using composite-id tag & Annotations
  • Hibernate Embeddable Composite Primary Key | @Embeddable, @EmbeddedId
  • Component Mapping in Hibernate Using Annotations | @Embeddable & @Embedded
  • Hibernate Component Mapping using XML
  • Difference between session.get() and session.load() in Hibernate

employee.hbm.xml

Place the employee.hbm.xml file under the src/main/resources folder

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  <hibernate-mapping package="com.javainterviewpoint">
    <class name="Employee" table="EMPLOYEE">
      <id name="id" column="ID">
        <generator class="native" />
      </id>
      <property name="name" column="NAME" />
      <property name="age" column="AGE" />
    </class>
 </hibernate-mapping>
  • The “employee.hbm.xml” tells hibernate to map “Employee.class” with the “EMPLOYEE” table in the database.
  • Next tag is the <id> tag, this tag tells which column needs to be marked as primary key in the database table, here our id property of the Employee class is the primary key. We have selected the generator as native, it takes the sequence in Oracle, if no sequence name is provided then “HIBERNATE_SEQUENCE” will be used
  • The property name, age are mapped with NAME, AGE columns in the table respectively.

department.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  <hibernate-mapping package="com.javainterviewpoint">
    <class name="Department" table="DEPARTMENT">
      <id name="dep_id" column="DEP_ID">
        <generator class="native"></generator>
      </id>
      <many-to-one name="Employee" class="com.javainterviewpoint.Employee" 
       not-null="true" column="emp_id" unique="true" cascade="all"></many-to-one>
     <property name="dep_name" column="DEP_NAME" />
     <property name="Designation" column="DESIGNATION" />
   </class>
 </hibernate-mapping>
  • The “department.hbm.xml” tells hibernate to map “Department.class” with the “DEPARTMENT” table in the database.
  • For the <id> tag we have selected the generator as native, so it takes the sequence in Oracle. Here our dep_id field act as a primary key.
  • We have used <many-to-one> tag with unique=”true” and not-null=”true” attributes this make many to one behave as one to one.
  • The property dep_id, dep_name, designation  are mapped with DEP_ID, DEP_NAME, DESIGNATION columns in the table respectively.

hibernate.cfg.xml

Place the hibernate.cfg.xml file also under the src/main/resources folder

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

<hibernate-configuration>

 <session-factory>

 <!-- Database connection settings -->
 <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
 <property name="hibernate.connection.username">root</property>
 <property name="hibernate.connection.password">root</property>
 <property name="hibernate.connection.url">jdbc:oracle:thin:@mydb:40051:dev</property>

 <!-- JDBC connection pool (use the built-in) -->
 <property name="connection.pool_size">1</property>

 <!-- SQL dialect -->
 <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>

 <!-- Echo all executed SQL to stdout -->
 <property name="show_sql">true</property>

 <!-- Drop and re-create the database schema on startup -->
 <property name="hibernate.hbm2ddl.auto">update</property>

 <!-- Mapping resource file -->
 <mapping resource="employee.hbm.xml" />
 <mapping resource="departement.hbm.xml" />
</session-factory> 
</hibernate-configuration>
  • First and foremost property is for specifying the JDBC Driver class, in my case it OracleDriver
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  • Give the connection URL for connecting the database and provide username and password for connecting the above database
<property name="hibernate.connection.url">jdbc:oracle:thin:@mydb:40051:dev</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
  • Specify the connection pool size, this property limits the number of connections in the Hibernate connection pool.
<property name="connection.pool_size">1</property>
  • Dialect Property makes the Hibernate generate the SQL for the corresponding database which is being used. In this example we are using Oracle database hence Oracle query will be generated. If you are using MySQL database then you need to change the dialect accordingly.
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
  • The show_sql property will print the executed sql in the console when set to true.
<property name="show_sql">true</property>
  • If the property “hibernate.hbm2ddl.auto” is set to “create”  This will drop and recreate the database schema on every execution. If it is set to “update” then the database schema will be updated every time rather than dropping and recreating.
<property name="hibernate.hbm2ddl.auto">update</property>
  • Under the Mapping resource tag  we need to specify all the mapping file for which we need the table to be created or updated.
<mapping resource="employee.hbm.xml" />
<mapping resource="department.hbm.xml" />

EmployeeHibernateOneToOne.java

package com.javainterviewpoint;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class EmployeeHibernateOneToOne
{
    public static void main(String args[])
    {
        //Reading the hibernate configuration file
        Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
        StandardServiceRegistryBuilder regBuilber = new StandardServiceRegistryBuilder();
        regBuilber.applySettings(configuration.getProperties());
        ServiceRegistry serviceRegistry = regBuilber.build();
        
        //Create SessionFacctory
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        
        //Create Session from SessionFactory
        Session session = sessionFactory.openSession();
        
        //Begin the transaction
        session.beginTransaction();
        
        //Create Employee object
        Employee employee = new Employee();
        
        //Set value to Employee class properties
        employee.setAge(102);
        employee.setName("JIP");
        
        //Create Department object
        Department  department = new Department();
        
        department.setDep_name("Manufacturing");
        department.setDesignation("Manufacturing Engineer");
        department.setEmployee(employee);
        //Persist the department object
        session.save(department);
        //Commit the changes
        session.getTransaction().commit();
        //Close the session
        session.close();
    }
}
  • Create the Configuration object and read the configuration file using the configure() method.
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
  • Get the SessionFactory object through the buildSessionFactory() method of the configuration object.
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
  • openSession() method opens up the new session and begin a new transaction
Session session = sessionFactory.openSession();
session.beginTransaction();
  • Create a new Employee object and set values to its properties
Employee employee = new Employee();
employee.setAge(102);
employee.setName("JIP");
  • Create a new Department object and set value to it properties
    Department  department = new Department();
    department.setDep_name("Manufacturing");
    department.setDesignation("Manufacturing Engineer");
  • save() method of the session object will persist the employee and department object into the database. Since we have used cascade as all
session.save(department);
  • Finally get the transaction and commit the changes and close the session.
session.getTransaction().commit();
session.close();

Console:

Nov 09, 2016 2:20:44 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: DEPARTMENT
Nov 09, 2016 2:20:44 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [dep_name, emp_id, dep_id, designation]
Nov 09, 2016 2:20:44 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: [fk_emp]
Nov 09, 2016 2:20:44 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [sys_c0014392]
Nov 09, 2016 2:20:47 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: EMPLOYEE
Nov 09, 2016 2:20:47 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [age, name, emp_id]
Nov 09, 2016 2:20:47 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
Nov 09, 2016 2:20:47 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [sys_c0014389]
Nov 09, 2016 2:20:47 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into EMPLOYEE (NAME, AGE, EMP_ID) values (?, ?, ?)
Hibernate: insert into DEPARTMENT (emp_id, DEP_NAME, DESIGNATION, DEP_ID) values (?, ?, ?, ?)

RetrieveEmployee.java

package com.javainterviewpoint;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class RetrieveEmployee
{
    public static void main(String args[])
    {
        //Reading the hibernate configuration file
        Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
        StandardServiceRegistryBuilder regBuilber = new StandardServiceRegistryBuilder();
        regBuilber.applySettings(configuration.getProperties());
        ServiceRegistry serviceRegistry = regBuilber.build();
        
        //Create SessionFacctory
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        
        //Create Session from SessionFactory
        Session session = sessionFactory.openSession();
        
        List departmentList = session.createQuery("from Department").list();
        for(Department department : departmentList)
        {
            System.out.println("*** Employee Details ***");
            Employee employee = (Employee)department.getEmployee();
            System.out.println("Employee ID   : "+employee.getEmp_id());
            System.out.println("Employee Name : "+employee.getName());
            System.out.println("Employee Age  : "+employee.getAge());
            
            System.out.println("*** Department Details***");
            System.out.println("Department ID   : "+department.getDep_id());
            System.out.println("Department Name : "+department.getDep_name());
            System.out.println("Designation     : "+department.getDesignation());
            
        }
        
        //Close the session
        session.close();
    }
}

Output:

Hibernate: select department0_.DEP_ID as DEP_ID1_0_, department0_.emp_id as emp_id2_0_, department0_.DEP_NAME as DEP_NAME3_0_, department0_.DESIGNATION as DESIGNATION4_0_ from DEPARTMENT department0_
*** Employee Details ***
Employee ID   : 83
Hibernate: select employee0_.EMP_ID as EMP_ID1_1_0_, employee0_.NAME as NAME2_1_0_, employee0_.AGE as AGE3_1_0_ from EMPLOYEE employee0_ where employee0_.EMP_ID=?
Employee Name : JIP
Employee Age  : 102
*** Department Details***
Department ID   : 82
Department Name : Manufacturing
Designation     : Manufacturing Engineer

Filed Under: Hibernate, Hibernate Tutorial, J2EE, Java Tagged With: Hibernate, Hibernate One to One

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·