DEV Community

Cover image for How to do a Select clause comparison of LocalDateTime in JPA
Adrian Matei for Codever

Posted on • Edited on • Originally published at codever.dev

3 1

How to do a Select clause comparison of LocalDateTime in JPA

The native SQL query we want to map in JPA is similar to the following:

select *
from PARTNER
where EVENT_TIMESTAMP >= timestamp '2021-09-17 10:00:00'
  and EVENT_TIMESTAMP < timestamp '2021-09-17 11:00:00'
Enter fullscreen mode Exit fullscreen mode

where the two timestamps should come as query parameters.

With JPA you can use a TypedQuery for example and set the LocalDateTime values to query parameters via the setParameter method:

@Stateless
public class PartnerDataRepository {

    @Inject private EntityManager em;

    public List<PartnerData> findPartnerDataWithinInterval(
      LocalDateTime fromDatetime, LocalDateTime toDatetime) {
        TypedQuery<PartnerData> query =
            em.createNamedQuery(
                PartnerData.FIND_PARTNER_DATA_IN_TIME_INTERVAL, PartnerData.class);

        query.setParameter(PartnerData.FROM_DATETIME, fromDatetime);
        query.setParameter(PartnerData.TO_DATETIME, toDatetime);

        return query.getResultList();
    }
}
Enter fullscreen mode Exit fullscreen mode

In the named query itself you can directly pass the parameters before : as usual, and the implementation (in my case Hibernate) takes care of the rest :

@Entity
@Access(AccessType.FIELD)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = PartnerData.TABLE_NAME)
@NamedQueries({
 @NamedQuery(
      name = PartnerKerndaten.FIND_PARTNER_DATA_IN_TIME_INTERVAL,
      query = "select m from PartnerData m where eventTimestamp >= :fromDatetime and eventTimestamp < :toDatetime")
})
public class PartnerData {
  public static final String TABLE_NAME = "PARTNER";

  public static final String FROM_DATETIME = "fromDatetime";
  public static final String TO_DATETIME = "toDatetime";

  public static final String FIND_PARTNER_DATA_IN_TIME_INTERVAL =
      "findPartnerDataWithinInterval";

  //... rest ignored for brevity
}
Enter fullscreen mode Exit fullscreen mode

Shared ❤️ from Codever. 👉 use the copy to mine functionality to add it to your personal snippets collection.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay