Core Java

Query JPA LocalDateTime Using LocalDate Example

Working with Java’s date and time API can be tricky, especially when your database column uses LocalDateTime but the query parameter coming from the user is a LocalDate. A common example is filtering events occurring on a given calendar day. If implemented incorrectly, Spring Data JPA will throw an exception because it cannot compare a LocalDateTime field with a LocalDate value.

This article explains why this error occurs and provides the correct methods for fixing it.

1. The Problem Scenario

Consider an Event entity with a LocalDateTime field, along with its corresponding JPA repository, service, and controller.

@Entity
public class Event {

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

    private String name;

    private LocalDateTime eventTime;
    
    // constructors, getters and setters
}

The Repository

public interface EventRepository extends JpaRepository<Event, Long> {

    public List<Event> findByEventTime(LocalDate date);

}

The Service

@Service
public class EventService {

    @Autowired
    private EventRepository eventRepository;

    public List<Event> getEventsByDate(LocalDate date) {
        return eventRepository.findByEventTime(date);
    }
}

The Controller

@RestController
@RequestMapping("/events")
public class EventController {

    private final EventService eventService;

    public EventController(EventService eventService) {
        this.eventService = eventService;
    }

    @GetMapping("/date")
    public List<Event> getByDate(@RequestParam("value")
            @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        return eventService.getEventsByDate(date);
    }
}

When you execute the request curl -X GET "http://localhost:8080/events/date?value=2025-11-09", Spring Boot attempts to invoke the repository method findByEventTime(LocalDate date), but since eventTime is a LocalDateTime field, JPA ends up comparing a LocalDateTime to a LocalDate, which leads to an unavoidable type mismatch error.

Example Error Output

[Request processing failed: org.springframework.dao.InvalidDataAccessApiUsageException: 
Argument [2025-11-09] of type 
[java.time.LocalDate] did not match parameter type [java.time.LocalDateTime (n/a)]] with root cause

org.hibernate.query.QueryArgumentException: Argument [2025-11-09] of type 
[java.time.LocalDate] did not match parameter type [java.time.LocalDateTime (n/a)]

This issue occurs because Spring Data JPA cannot bind a LocalDate to a LocalDateTime column. A LocalDate contains only the date, while a LocalDateTime includes both date and time. Since the database stores full timestamps (e.g., 2025-11-09 14:20:00), JPA cannot perform a direct comparison such as event_time = '2025-11-09', as the input lacks a time component, making the comparison invalid.

2. Practical Ways to Fix the Problem

There are several reliable approaches to querying a LocalDateTime field using a LocalDate. Each method provides a way to handle the missing time portion in the query properly.

2.1 Use a Range Query

A reliable way to query events that occur on a specific date is to convert the LocalDate into a full-day range. By calculating the start and end of the day, we can safely retrieve all LocalDateTime values that fall within that time window.

Updated Repository

The repository method is modified to accept two LocalDateTime values, allowing us to fetch all events between the start and end of the selected date.

public interface EventRepository extends JpaRepository<Event, Long> {

    List<Event> findByEventTimeBetween(LocalDateTime start, LocalDateTime end);
}

Updated Service

The service layer computes the full 24-hour range for the provided date, converting it into valid LocalDateTime boundaries.

@Service
public class EventService {

    @Autowired
    private EventRepository eventRepository;

    public List<Event> getEventsByDate(LocalDate date) {
        LocalDateTime start = date.atStartOfDay();
        LocalDateTime end = date.plusDays(1).atStartOfDay();
        return eventRepository.findByEventTimeBetween(start, end);
    }

}

Use a JPQL Range Query

Another reliable way to match a LocalDateTime field with a specific date is to use a JPQL query that operates within a start and end range.

public interface EventRepository extends JpaRepository<Event, Long> {

        @Query("SELECT e FROM Event e "
            + "WHERE e.eventTime >= :dateStart AND e.eventTime < :dateEnd")
    List<Event> findByDate(
            @Param("dateStart") LocalDateTime start,
            @Param("dateEnd") LocalDateTime end);

}

This JPQL query receives two LocalDateTime values representing the beginning and end of the target day. It fetches all records where eventTime falls within this range using an inclusive lower bound and an exclusive upper bound. This approach works consistently across all JPA-supported databases and ensures that all timestamps on the chosen date are correctly included.

2.2 Using JPQL With Database DATE() Function

Some databases allow the extraction of the date portion from a timestamp using DATE(). This allows a direct comparison between a LocalDate and the date-only part of a LocalDateTime.

@Query("SELECT e FROM Event e WHERE FUNCTION('DATE', e.eventTime) = :date")
List<Event> findByDate(@Param("date") LocalDate date);

Note: Not all JPA providers and databases support the DATE() function in JPQL, and using functions on columns can prevent the database from using indexes, which may result in slower queries.

Cast the Timestamp (Database-Specific)

If you do not need database portability and want the simplest SQL expression, you can cast the timestamp to a date type, provided your database supports it (e.g., H2, PostgreSQL).

public interface EventRepository extends JpaRepository<Event, Long> {

    @Query("SELECT e FROM Event e WHERE CAST(e.eventTime AS date) = :date")
    List<Event> findByDate(@Param("date") LocalDate date);
}

This approach is convenient for quick lookups, but it depends on database-specific date functions and may impact index usage.

With the above fixes applied, this request will now correctly return all events occurring on 2025-11-09, regardless of the time stored in the database.

curl -X GET "http://localhost:8080/events/date?value=2025-11-09"

3. Conclusion

Querying a LocalDateTime column with a LocalDate value will fail because the types are incompatible. Spring Data JPA cannot compare a timestamp to a date without knowing the time range. The proper solution is to convert the LocalDate into a start and end range for the day or use an explicit query.

4. Download the Source Code

This article covered how to query a LocalDateTime field in Java Persistence Applications (JPA) using a LocalDate value.

Download
You can download the full source code of this example here: java jpa query localdatetime with localdate

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button