DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Implement Hibernate Second-Level Cache With NCache
  • Architectural Miscalculation and Hibernate Problem "Type UUID but Expression Is of Type Bytea"
  • How to Store Text in PostgreSQL: Tips, Tricks, and Traps
  • Simplify Java Persistence Using Quarkus and Hibernate Reactive

Trending

  • SSRF Prevention in C#: Securing File Imports From User-Supplied URLs
  • Why Spark Executors Leave Cores Idle on YARN: A Packing Model for Executor Sizing
  • Beyond the Endpoint: How Agent Cards Enable Discovery, Interoperability, and Trust
  • Solving Comprehension Debt in AI-Generated Codebases

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Databases
  4. Properly Persisting LocalDateTime to Oracle DATE Column With Hibernate 5

Properly Persisting LocalDateTime to Oracle DATE Column With Hibernate 5

Let's take a look at a tutorial that explores properly persisting LocalDateTime to Oracle DATE column with Hibernate 5.

By 
Samuel Martin
·
Oct. 11, 18 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
21.3K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Context

In my current Java project, I'm using hibernate to persist a Java LocalDateTime to an Oracle DATE type column.

Out of the box, everything seems to work well, but when the amount of data in the queried table increases, the execution time drastically increases as well.

The technical context is: Java 8, Hibernate 5, and Oracle 11g.

Analysis

After an analysis of the explain plan by a DBA, it seemed that the query was not using the proper index created on the DATE column.

I did some research and found the useful post below:

https://blog.jooq.org/2014/12/29/leaky-abstractions-or-how-to-bind-oracle-date-correctly-with-hibernate/

The problem was located at the binding level when Hibernate prepared the query.

java.time.LocalDateTime is converted to java.sql.Timestamp and finally bound to oracle.sql.TIMESTAMP.

Our column has oracle.sql.DATE type so there is an implicit conversion in Oracle to perform the query causing the index not to be used.

Solutions

Change Type

The first solution is the simpler one: change the column type to TIMESTAMP.

Unfortunately, this is not always possible.

Custom Hibernate Type

The second solution is to create a Hibernate custom type in order to control the binding of the field.

Annotate the field of your entity with @Type

And org.mycompany.util.LocalDateTimeUserType is a custom Hibernate UserType:

import oracle.sql.DATE;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.usertype.EnhancedUserType;

import java.io.Serializable;
import java.sql.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class LocalDateTimeUserType implements EnhancedUserType, Serializable {

    private static final int[] SQL_TYPES = new int[] {
        Types.TIMESTAMP
    };

    @Override
    public String objectToSQLString(Object o) {
        throw new UnsupportedOperationException();
    }

    @Override
    public String toXMLString(Object o) {
        return o.toString();
    }

    @Override
    public Object fromXMLString(String s) {
        return LocalDateTime.parse(s);
    }

    @Override
    public int[] sqlTypes() {
        return SQL_TYPES;
    }

    @Override
    public Class returnedClass() {
        return LocalDateTime.class;
    }

    @Override
    public boolean equals(Object x, Object y) throws HibernateException {
        if (x == y) {
            return true;
        }
        if (x == null || y == null) {
            return false;
        }
        LocalDateTime dtx = (LocalDateTime) x;
        LocalDateTime dty = (LocalDateTime) y;
        return dtx.equals(dty);
    }

    @Override
    public int hashCode(Object o) throws HibernateException {
        return o.hashCode();
    }

    @Override
    public Object nullSafeGet(ResultSet resultSet, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
        Object timestamp = StandardBasicTypes.TIMESTAMP.nullSafeGet(resultSet, names, session, owner);
        if (timestamp == null) {
            return null;
        }
        Date ts = (Date) timestamp;
        Instant instant = Instant.ofEpochMilli(ts.getTime());
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

    @Override
    public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
        if (value == null) {
            StandardBasicTypes.TIMESTAMP.nullSafeSet(preparedStatement, null, index, session);
        } else {
            LocalDateTime ldt = ((LocalDateTime) value);
            preparedStatement.setObject(index, new DATE(Timestamp.valueOf(ldt)));
        }
    }

    @Override
    public Object deepCopy(Object o) throws HibernateException {
        return o;
    }

    @Override
    public boolean isMutable() {
        return false;
    }

    @Override
    public Serializable disassemble(Object o) throws HibernateException {
        return (Serializable) o;
    }

    @Override
    public Object assemble(Serializable serializable, Object o) throws HibernateException {
        return serializable;
    }

    @Override
    public Object replace(Object o, Object o1, Object o2) throws HibernateException {
        return o;
    }
}

Conclusion

When using Oracle, the choice of a column type could have important consequences on queries performance, especially with DATE type.

If you need to store Date and Time, prefer the TIMESTAMP type and use Java LocalDateTime.

If Date only is enough, Oracle DATE type is ok.

Database Hibernate

Opinions expressed by DZone contributors are their own.

Related

  • Implement Hibernate Second-Level Cache With NCache
  • Architectural Miscalculation and Hibernate Problem "Type UUID but Expression Is of Type Bytea"
  • How to Store Text in PostgreSQL: Tips, Tricks, and Traps
  • Simplify Java Persistence Using Quarkus and Hibernate Reactive

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook