Share on Google+Share on Google+

Hibernate Date Format

This section contains description of Hibernate Date Format.

Hibernate Date Format

This section contains description of Hibernate Date Format.

Hibernate Date Format :

When you save date to the database using hibernate, the date is converted to local time and stored.
Suppose your date is '12-06-2012' ,hibernate inserts it into database in default format of"yyyy-mm-dd".
Timestamp format is yyyy-mm-dd hh:mm:ss.

Timestamp format takes 4 byte whereas DtaeTimeFormat takes 8 byte.

Hibernate provides date type annotation which takes format 'yyyy-mm-dd'

@Type(type = "date")
@Column(name = "date_of_join")
private Date dateOfJoin;

Example : In this example we are selecting employee whose id is 1 and displaying date in different format.

package net.roseindia.main;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import net.roseindia.table.Employee;
import net.roseindia.util.HibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class HibernateDateFormat {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();;

try {
String hql = "SELECT emp from Employee emp WHERE";
Query query1 = session.createQuery(hql);
List<Employee> objectList = query1.list();
Iterator iterator = objectList.iterator();
Employee employee = (Employee);
Date date = employee.getDateOfJoin();
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String dateBufferString = format.format(date);
Date dateBuffer;
try {

dateBuffer = format.parse(dateBufferString);
System.out.println("Database Date Format :" + date);
System.out.println("(dd-MM-yyyy) date: " + format.format(date));
System.out.println("dateBufferSTring " + dateBufferString);
System.out.println("dateBuffer: " + dateBuffer);

} catch (ParseException e) {
// TODO Auto-generated catch block
} catch (HibernateException e) {
// TODO: handle exception
} finally {

Output :

Hibernate: select employee0_.emp_id as emp1_0_, employee0_.date_of_join as date2_0_, as name0_, employee0_.salary as salary0_ from employee employee0_ where employee0_.emp_id=1
Database Date Format :2010-03-12
(dd-MM-yyyy) date: 12-03-2010
dateBufferSTring 12-03-2010
dateBuffer: Fri Mar 12 00:00:00 IST 2010

Click here to download complete source code



Posted on: August 1, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Hibernate Date Format  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image