Friday 26 December 2014

Hibernate : One-to-One mapping


In a one-to-one relationship, each row in one database table is linked to 1 and only 1 other row in another table. Let’s say I had employee table and department table, one employee can work in one department.

package myFirstHibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Department {
  @Id @GeneratedValue
  private int departmentId;
  private String departmentName;
  
  public int getDepartmentId() {
    return departmentId;
  }
  
  public void setDepartmentId(int departmentId) {
    this.departmentId = departmentId;
  }
  
  public String getDepartmentName() {
    return departmentName;
  }
  
  public void setDepartmentName(String departmentName) {
    this.departmentName = departmentName;
  }
  
}

package myFirstHibernate;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;

@Entity
public class Employee {
  @Id @GeneratedValue
  private int id;
  private String firstName;
  private String lastName;
  
  @OneToOne(cascade = CascadeType.ALL)
  Department department;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  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 Department getDepartment() {
    return department;
  }

  public void setDepartment(Department department) {
    this.department = department;
  }
  
}


hibernate.cfg.xml
<?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="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost/sample</property>
    <property name="connection.username">root</property>
    <property name="connection.password">tiger</property>
    
    <!-- Enable the logging of all the generated SQL statements to the console -->
    <property name="show_sql">true</property>
    
    <!-- Format the generated SQL statement to make it more readable, -->
    <property name="format_sql">false</property>
    
    <!-- Hibernate will put comments inside all generated SQL statements to hint what’s the generated SQL trying to do -->
    <property name="use_sql_comments">false</property>
    
    <!-- This property makes Hibernate generate the appropriate SQL for the chosen database. -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    
    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">create</property>
    
    <!-- mappings for annotated classes -->
    <mapping class="myFirstHibernate.Employee" />
    <mapping class="myFirstHibernate.Department" />
    
  </session-factory>
  
</hibernate-configuration>

package myFirstHibernate;

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

public class TestEmployee {
  
  /* Step 1: Create session factory */
  private static SessionFactory getSessionFactory() {
    Configuration configuration = new Configuration().configure();
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
    applySettings(configuration.getProperties());
    SessionFactory factory = configuration.buildSessionFactory(builder.build());
        return factory;
    }
  
  public static void main(String args[]){
    Employee emp1 = new Employee();
    Department dept = new Department();
    
    dept.setDepartmentName("Research And Development");
    emp1.setFirstName("Hari Krishna");
    emp1.setLastName("Gurram");
    emp1.setDepartment(dept);
    
    /* To persist data */
    SessionFactory sessionFactory = getSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.save(emp1);
    session.getTransaction().commit();
    session.close(); 
    
  }
}

Run TestEmployee class, you will get output like below.
Hibernate: alter table Employee drop foreign key FK_llgx6he23yhuibn2piko3sgl2
Hibernate: drop table if exists Department
Hibernate: drop table if exists Employee
Hibernate: create table Department (departmentId integer not null auto_increment, departmentName varchar(255), primary key (departmentId))
Hibernate: create table Employee (id integer not null auto_increment, firstName varchar(255), lastName varchar(255), department_departmentId integer, primary key (id))
Hibernate: alter table Employee add constraint FK_llgx6he23yhuibn2piko3sgl2 foreign key (department_departmentId) references Department (departmentId)
Dec 21, 2014 12:15:23 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into Department (departmentName) values (?)
Hibernate: insert into Employee (department_departmentId, firstName, lastName) values (?, ?, ?)


MySQL structures like below.
mysql> select * from department;
+--------------+--------------------------+
| departmentId | departmentName           |
+--------------+--------------------------+
|            1 | Research And Development |
+--------------+--------------------------+
1 row in set (0.00 sec)

mysql> select * from employee;
+----+--------------+----------+-------------------------+
| id | firstName    | lastName | department_departmentId |
+----+--------------+----------+-------------------------+
|  1 | Hari Krishna | Gurram   |                       1 |
+----+--------------+----------+-------------------------+
1 row in set (0.00 sec)

mysql> describe department;
+----------------+--------------+------+-----+---------+----------------+
| Field          | Type         | Null | Key | Default | Extra          |
+----------------+--------------+------+-----+---------+----------------+
| departmentId   | int(11)      | NO   | PRI | NULL    | auto_increment |
| departmentName | varchar(255) | YES  |     | NULL    |                |
+----------------+--------------+------+-----+---------+----------------+
2 rows in set (0.01 sec)

mysql> describe employee;
+-------------------------+--------------+------+-----+---------+----------------+
| Field                   | Type         | Null | Key | Default | Extra          |
+-------------------------+--------------+------+-----+---------+----------------+
| id                      | int(11)      | NO   | PRI | NULL    | auto_increment |
| firstName               | varchar(255) | YES  |     | NULL    |                |
| lastName                | varchar(255) | YES  |     | NULL    |                |
| department_departmentId | int(11)      | YES  | MUL | NULL    |                |
+-------------------------+--------------+------+-----+---------+----------------+
4 rows in set (0.01 sec)

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment