Hibernate Date, Time and DateTime Mapping

摘要: In this tutorial we show how to work with java.lang.Date to store Date, Time and DateTime using Hibernate Annotations or XML Mappings. Hibernate allows various Java Date/Time classes to be mapped. Like the java.sql.Date, java.sql.Time or java.sql.Timestamp. But to avoid dependencies on the java.sql package, it’s common to use java.util or java.time Date/Time classes instead.

In this tutorial we show how to work with java.lang.Date to store Date, Time and DateTime using Hibernate Annotations or XML Mappings. Hibernate allows various Java Date/Time classes to be mapped. Like the java.sql.Date, java.sql.Time or java.sql.Timestamp. But to avoid dependencies on the java.sql package, it’s common to use java.util or java.time Date/Time classes instead.

Maven Dependencies

We use Apache Maven to manage the projects dependencies. Add the following dependencies to your projects pom.xml file.

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.4</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.2.3.Final</version>
</dependency>

Create Model Classes + Annotation Mappings

We can use the @Temporal annotation to specify the precision in which hibernate will save the date, time or timestamp. In the following java class we show you each type. If you’re interested in how these types will be saved in the database, you can immediately scroll to the bottom of the page to see the result.

  • TemporalType.DATE: maps the date as java.sql.Date.
  • TemporalType.TIME: maps the date as java.sql.Time.
  • TemporalType.TIMESTAMP: maps the date as java.sql.Timestamp.
package com.memorynotfound.hibernate;

import javax.persistence.*;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Date;

@Entity
public class DateAndTime {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Temporal(TemporalType.DATE)
    private Date date;
    @Temporal(TemporalType.TIME)
    private Date time;
    @Temporal(TemporalType.TIMESTAMP)
    private Date dateTime;


    public DateAndTime() {
    }

    public DateAndTime(Date date, Date time, Date dateTime) {
        this.date = date;
        this.time = time;
        this.dateTime = dateTime;
    }

    public Integer getId() {
        return id;
    }

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

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public Date getTime() {
        return time;
    }

    public void setTime(Date time) {
        this.time = time;
    }

    public Date getDateTime() {
        return dateTime;
    }

    public void setDateTime(Date dateTime) {
        this.dateTime = dateTime;
    }

    @Override
    public String toString() {
        return "DateAndTime{" +
                "id=" + id +
                ", date=" + date +
                ", time=" + time +
                ", dateTime=" + dateTime +
                '}';
    }
}

Hibernate HBM XML Mapping

If you prefer Hibernate XML HBM Mapping files over Annotations, you can use the equivalent hibernate xml mapping. This file is located in the src/main/resources folder and is named DateAndTime.hbm.xml.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.memorynotfound.hibernate.DateAndTime">

        <id name="id" type="java.lang.Integer">
            <generator class="identity" />
        </id>

        <property name="date" type="date"/>
        <property name="time" type="time"/>
        <property name="dateTime" type="timestamp"/>

    </class>
</hibernate-mapping>

Configure Hibernate Connection Properties

We can configure the database properties using the hibernate hibernate.cfg.xml file, located on the classpath in 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 properties -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/datestore?serverTimezone=Europe/Brussels</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password"></property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- show mysql queries output in console -->
        <property name="hibernate.show_sql">true</property>

        <!-- manage automatic database creation -->
        <property name="hibernate.hbm2ddl.auto">create-drop</property>

        <!-- add annotated resources here -->
        <mapping class="com.memorynotfound.hibernate.DateAndTime"/>

    </session-factory>
</hibernate-configuration>

HibernateUtil

This class is used to configure hibernate during startup and create a standalone SessionFactory.

package com.memorynotfound.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() throws HibernateException {
        return sessionFactory.openSession();
    }

    public static void shutdown() {
        sessionFactory.close();
    }
}

Create app

Finally, we can test the application by creating a new object and setting the corresponding fields. When the object is persisted, we can see the result in the database.

package com.memorynotfound.hibernate;

import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class App {

    public static void main (String...args){

        Session session = HibernateUtil.getSession();
        Transaction tx = session.beginTransaction();

        Date now = new Date();

        DateAndTime date = new DateAndTime();
        date.setDate(now);
        date.setTime(now);
        date.setDateTime(now);

        session.save(date);
        tx.commit();

        List<DateAndTime> dateAndTimes = (List<DateAndTime>)session.createQuery("from DateAndTime").list();
        System.out.println(Arrays.toString(dateAndTimes.toArray()));

        session.close();
        HibernateUtil.shutdown();
    }
}

The previous application prints the following info to the console.

...
Hibernate: insert into DateAndTime (date, time, dateTime) values (?, ?, ?)
Hibernate: select dateandtim0_.id as id1_0_, dateandtim0_.date as date2_0_, dateandtim0_.time as time3_0_, dateandtim0_.dateTime as dateTime4_0_ from DateAndTime dateandtim0_
[DateAndTime{id=1, date=Mon Oct 24 11:34:49 CEST 2016, time=Mon Oct 24 11:34:49 CEST 2016, dateTime=Mon Oct 24 11:34:49 CEST 2016}]
...

Records inserted in the database

Download

上一篇: Mapping Enum Types with Hibernate Example
下一篇: Hibernate One to One Unidirectional Shared Primary Key
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号