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

  • Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL

Trending

  • MySQL Instant DDL: Metadata Locks, Waiting Writers, and Query Pileups
  • Delegated Transport, Forked Authorization: Where Chat and AI-Agent Integrations Actually Break
  • Microsoft Fabric Throttling: Diagnose Before You Scale
  • PWA on iOS, Part 1: PWAs on the iPhone Are Older Than They Look

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. Coding
  3. Java
  4. Dealing With Java's LocalDateTime in JPA

Dealing With Java's LocalDateTime in JPA

Trying to persist Java 8 LocalDateTime with JPA can produce surprising results. To prevent this, we need a special converter present on the classpath.

By 
MD Sayem Ahmed
·
Mar. 16, 17 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
89.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

A few days ago, I ran into a problem while dealing with a LocalDateTime attribute in JPA. In this blog post, I will try to create a sample problem to explain the issue, along with the solution that I used.

Consider the following entity, which models an Employee of a certain company:

@Entity
@Getter
@Setter
public class Employee {

  @Id
  @GeneratedValue
  private Long id;
  private String name;
  private String department;
  private LocalDateTime joiningDate;
}


I was using Spring Data JPA, so created the following repository:

@Repository
public interface EmployeeRepository 
    extends JpaRepository<Employee, Long> {

}


I wanted to find all employees who have joined the company at a particular date. To do that I extended my repository from JpaSpecificationExecutor:

@Repository
public interface EmployeeRepository 
    extends JpaRepository<Employee, Long>,
    JpaSpecificationExecutor<Employee> {

}


...and wrote a query like this:

@SpringBootTest
@RunWith(SpringRunner.class)
@Transactional
public class EmployeeRepositoryIT {

  @Autowired
  private EmployeeRepository employeeRepository;

  @Test
  public void findingEmployees_joiningDateIsZeroHour_found() {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime joiningDate = LocalDateTime.parse("2014-04-01 00:00:00", formatter);

    Employee employee = new Employee();
    employee.setName("Test Employee");
    employee.setDepartment("Test Department");
    employee.setJoiningDate(joiningDate);
    employeeRepository.save(employee);

    // Query to find employees
    List<Employee> employees = employeeRepository.findAll((root, query, cb) ->
        cb.and(
            cb.greaterThanOrEqualTo(root.get(Employee_.joiningDate), joiningDate),
            cb.lessThan(root.get(Employee_.joiningDate), joiningDate.plusDays(1)))
    );

    assertThat(employees).hasSize(1);
  }
}


The above test passed without any problem. However, the following test failed (which was supposed to pass):

@Test
public void findingEmployees_joiningDateIsNotZeroHour_found() {
  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  LocalDateTime joiningDate = LocalDateTime.parse("2014-04-01 08:00:00", formatter);
  LocalDateTime zeroHour = LocalDateTime.parse("2014-04-01 00:00:00", formatter);

  Employee employee = new Employee();
  employee.setName("Test Employee");
  employee.setDepartment("Test Department");
  employee.setJoiningDate(joiningDate);
  employeeRepository.save(employee);

  List<Employee> employees = employeeRepository.findAll((root, query, cb) ->
      cb.and(
          cb.greaterThanOrEqualTo(root.get(Employee_.joiningDate), zeroHour),
          cb.lessThan(root.get(Employee_.joiningDate), zeroHour.plusDays(1))
      )
  );

  assertThat(employees).hasSize(1);
}


The only thing that is different from the previous test is that in the previous test I used the zero hour as the joining date, and here I used 8 a.m.

At first, it seemed weird to me. The tests seemed to pass whenever the joining date of an employee was set to a zero hour of a day, but failed whenever it was set to any other time.

In order to investigate the problem, I turned on Hibernate logging to see the actual query and the values being sent to the database, and noticed something like this in the log:

2017-03-05 22:26:20.804 DEBUG 8098 --- [           main] org.hibernate.SQL:
    select
        employee0_.id as id1_0_,
        employee0_.department as departme2_0_,
        employee0_.joining_date as joining_3_0_,
        employee0_.name as name4_0_
    from
        employee employee0_
    where
        employee0_.joining_date>=?
        and employee0_.joining_dateHibernate:
    select
        employee0_.id as id1_0_,
        employee0_.department as departme2_0_,
        employee0_.joining_date as joining_3_0_,
        employee0_.name as name4_0_
    from
        employee employee0_
    where
        employee0_.joining_date>=?
        and employee0_.joining_date2017-03-05 22:26:20.806 TRACE 8098 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARBINARY] - [2014-04-01T00:00]
2017-03-05 22:26:20.807 TRACE 8098 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [2] as [VARBINARY] - [2014-04-02T00:00]


It was evident that JPA was NOT treating the joiningDate attribute as a date or time, but as a VARBINARY type. This is why the comparison to an actual date was failing.

In my opinion, this is not a very good design. Rather than throwing something like UnsupportedAttributeException or whatever, it was silently trying to convert the value to something else, and thus failing the comparison at random (well, not exactly random). This type of bug is hard to find in the application unless you have a strong suite of automated tests, which was, fortunately, my case.

Back to the problem now. The reason JPA was failing to convert LocalDateTime appropriately was very simple. The last version of the JPA specification (which is 2.1) was released before Java 8, and as a result, it cannot handle the new Date and Time API.

To solve the problem, I created a custom converter implementation which converts the LocalDateTime to java.sql.Timestamp before saving it to the database, and vice versa. That solved the problem.

@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {

  @Override
  public Timestamp convertToDatabaseColumn(LocalDateTime localDateTime) {
    return Optional.ofNullable(localDateTime)
        .map(Timestamp::valueOf)
        .orElse(null);
  }

  @Override
  public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {
    return Optional.ofNullable(timestamp)
        .map(Timestamp::toLocalDateTime)
        .orElse(null);
  }
}


The above converter will be automatically applied whenever I try to save a LocalDateTime attribute. I could also explicitly mark the attributes that I wanted to convert explicitly, using the javax.persistence.Convert annotation:

@Convert(converter = LocalDateTimeConverter.class)
private LocalDateTime joiningDate;


The full code is available at GitHub.

Java (programming language)

Published at DZone with permission of MD Sayem Ahmed. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL

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