Thursday 25 December 2014

@EmbeddedId : Represent embedded object as primary key


If you want to use another object as primary key for your entity class, then you have to use @EmbeddedId annotation.

package myFirstHibernate;

import java.io.Serializable;

public class EmployeeKey implements Serializable{
  private int empId;
  private int deptId;
  
  public int getEmpId() {
    return empId;
  }
  
  public void setEmpId(int empId) {
    this.empId = empId;
  }
  
  public int getDeptId() {
    return deptId;
  }
  
  public void setDeptId(int deptId) {
    this.deptId = deptId;
  }
  
}

package myFirstHibernate;

import javax.persistence.EmbeddedId;
import javax.persistence.Entity;

@Entity
public class Employee {
  @EmbeddedId
  private EmployeeKey empKey;
  private String firstName;
  private String lastName;
  
  public EmployeeKey getEmpKey() {
    return empKey;
  }
  
  public void setEmpKey(EmployeeKey empKey) {
    this.empKey = empKey;
  }
  
  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;
  }
    
}


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" />
    
  </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();
    EmployeeKey empKey = new EmployeeKey();
    empKey.setDeptId(1);
    empKey.setEmpId(358);
    emp1.setEmpKey(empKey);
    emp1.setFirstName("Hari Krishna");
    emp1.setLastName("Gurram");
    
    /* To persisit 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: drop table if exists Employee
Hibernate: create table Employee (deptId integer not null, empId integer not null, firstName varchar(255), lastName varchar(255), primary key (deptId, empId))
Dec 20, 2014 10:34:28 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into Employee (firstName, lastName, deptId, empId) values (?, ?, ?, ?)


Table in MySQL looks like below.


mysql> select * from employee;
+--------+-------+--------------+----------+
| deptId | empId | firstName    | lastName |
+--------+-------+--------------+----------+
|      1 |   358 | Hari Krishna | Gurram   |
+--------+-------+--------------+----------+
1 row in set (0.00 sec)
mysql> describe employee;
+-----------+--------------+------+-----+---------+-------+
| Field     | Type         | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| deptId    | int(11)      | NO   | PRI | NULL    |       |
| empId     | int(11)      | NO   | PRI | NULL    |       |
| firstName | varchar(255) | YES  |     | NULL    |       |
| lastName  | varchar(255) | YES  |     | NULL    |       |
+-----------+--------------+------+-----+---------+-------+
4 rows in set (0.15 sec)
Prevoius                                                 Next                                                 Home

No comments:

Post a Comment