Wednesday 24 December 2014

Temporal : Handling date in Hibernate


Let’s see how Hibernate stores fields of type Date into database first.

package myFirstHibernate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Date;

@Entity
public class Employee {
 @Id
 @Column(name="emp_id")
 private int id;
 private String firstName;
 private String lastName;
 private String designation;
 private int age;
 private double salary;
 private Date joiningDate;
 
 public Date getJoiningDate() {
  return joiningDate;
 }

 public void setJoiningDate(Date joiningDate) {
  this.joiningDate = joiningDate;
 }

 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 String getDesignation() {
  return designation;
 }
 
 public void setDesignation(String designation) {
  this.designation = designation;
 }
 
 public int getAge() {
  return age;
 }
 
 public void setAge(int age) {
  this.age = age;
 }
 
 public double getSalary() {
  return salary;
 }
 
 public void setSalary(double salary) {
  this.salary = salary;
 }
 
}


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>


TestEmployee.java
package myFirstHibernate;

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

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();
  emp1.setAge(26);
  emp1.setDesignation("Senior Software Developer");
  emp1.setFirstName("Hari Krishna");
  emp1.setId(1);
  emp1.setLastName("Gurram");
  emp1.setSalary(80000);
  emp1.setJoiningDate(new Date());
  
  SessionFactory sessionFactory = getSessionFactory();
  Session session = sessionFactory.openSession();
  session.beginTransaction();
  session.save(emp1);
  session.getTransaction().commit();
  session.close();  
 }
}


Run “TestEmployee.java” you will get output like below.

Hibernate: drop table if exists Employee
Hibernate: create table Employee (emp_id integer not null, age integer not null, designation varchar(255), firstName varchar(255), joiningDate datetime, lastName varchar(255), salary double precision not null, primary key (emp_id))
Dec 20, 2014 12:08:18 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into Employee (age, designation, firstName, joiningDate, lastName, salary, emp_id) values (?, ?, ?, ?, ?, ?, ?)


As you observe output, joiningDate is stored as type datetime.

You can check table Employee in MySQL.

mysql> select * from employee;
+--------+-----+---------------------------+--------------+---------------------+----------+--------+
| emp_id | age | designation               | firstName    | joiningDate         | lastName | salary |
+--------+-----+---------------------------+--------------+---------------------+----------+--------+
|      1 |  26 | Senior Software Developer | Hari Krishna | 2014-12-20 00:08:16 | Gurram   |  80000 |
+--------+-----+---------------------------+--------------+---------------------+----------+--------+
1 row in set (0.22 sec)


Date is stored as yyyy-mm-dd hh:mm:ss format.  Sometimes you want to store only yyyy-mm-dd,  (or) only time hh:mm:ss etc.

You can handle this by using “Temporal” annotation.

@Temporal(TemporalType.DATE)
private Date joiningDate;

Above snippet store only date.
  
@Temporal(TemporalType.TIME)
private Date joiningDate;

Above snippet store only time.

Change Employee class by updating “joiningDate”.

package myFirstHibernate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import java.util.Date;

@Entity
public class Employee {
 @Id
 @Column(name="emp_id")
 private int id;
 private String firstName;
 private String lastName;
 private String designation;
 private int age;
 private double salary;
 
 @Temporal(TemporalType.DATE)
 private Date joiningDate;
 
 public Date getJoiningDate() {
  return joiningDate;
 }

 public void setJoiningDate(Date joiningDate) {
  this.joiningDate = joiningDate;
 }

 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 String getDesignation() {
  return designation;
 }
 
 public void setDesignation(String designation) {
  this.designation = designation;
 }
 
 public int getAge() {
  return age;
 }
 
 public void setAge(int age) {
  this.age = age;
 }
 
 public double getSalary() {
  return salary;
 }
 
 public void setSalary(double salary) {
  this.salary = salary;
 }
 
}

Re run “TestEmployee” class, you will get output like below
Hibernate: drop table if exists Employee
Hibernate: create table Employee (emp_id integer not null, age integer not null, designation varchar(255), firstName varchar(255), joiningDate date, lastName varchar(255), salary double precision not null, primary key (emp_id))
Dec 20, 2014 12:31:13 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into Employee (age, designation, firstName, joiningDate, lastName, salary, emp_id) values (?, ?, ?, ?, ?, ?, ?)


Open MySQL prompt and check for employee table, you can observe it stores only date this time.


mysql> SELECT * FROM employee;
+--------+-----+---------------------------+--------------+-------------+----------+--------+
| emp_id | age | designation               | firstName    | joiningDate | lastName | salary |
+--------+-----+---------------------------+--------------+-------------+----------+--------+
|      1 |  26 | Senior Software Developer | Hari Krishna | 2014-12-20  | Gurram   |  80000 |
+--------+-----+---------------------------+--------------+-------------+----------+--------+
1 row in set (0.00 sec)

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment