使用 JPA 查找今​​天生日的用户

发布于 2024-08-27 10:46:54 字数 900 浏览 4 评论 0原文

我有一个包含用户的表,并正在尝试获取今天过生日的人的列表,以便应用程序可以发送电子邮件。

用户被定义为

@Entity
public class User {

    @Size(max = 30)
    @NotNull
    private String name;

    [...]
    @Temporal(TemporalType.DATE)
    @DateTimeFormat(style = "S-")
    protected Date birthday;
}

,我有一个方法可以返回今天出生的人,就像这样

@SuppressWarnings("unchecked")
public static List<User> findUsersWithBirthday() {

 List<User> users = 
  entityManager().createQuery("select u from User u where u.birthday = :date")
    .setParameter("date", new Date(), TemporalType.DATE)
    .getResultList();
  return users;
}

这很好,所有这些都可以找到今天出生的人,但是这并不是那么有用,所以我一直在努力寻找一个查找今天出生的所有用户的方法,与年份无关。

使用MySQL,我可以使用类似的函数,

select month(curdate()) as month, dayofmonth(curdate()) as day

但是我一直在努力寻找与此等效的JPA。

我正在使用 Spring 3.0.1 和 Hibernate 3.3.2

I have a table with users and are trying to get a list with the people who have birthday today so the app can send an email.

The User is defined as

@Entity
public class User {

    @Size(max = 30)
    @NotNull
    private String name;

    [...]
    @Temporal(TemporalType.DATE)
    @DateTimeFormat(style = "S-")
    protected Date birthday;
}

and I've got a method which returns the people which were born today like so

@SuppressWarnings("unchecked")
public static List<User> findUsersWithBirthday() {

 List<User> users = 
  entityManager().createQuery("select u from User u where u.birthday = :date")
    .setParameter("date", new Date(), TemporalType.DATE)
    .getResultList();
  return users;
}

This is fine and all for finding people which were born today, however tha's not really that useful, so I've been struggling for a way to find all the users that were born today, independent of the year.

Using MySQL there's functions I can use like

select month(curdate()) as month, dayofmonth(curdate()) as day

However I've been struggling to find a JPA equivalent to that.

I'm using Spring 3.0.1 and Hibernate 3.3.2

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

少钕鈤記 2024-09-03 10:46:54

我不知道如何在 JPQL 中执行此操作,但 HQL 有 day()month() 函数,因此您可以运行:

from User u 
where day(u.birthday) = day(CURRENT_DATE) 
and month(u.birthday) = month(CURRENT_DATE) 

如果不能使用 HQL,我将进行本机查询。

I don't know how to do that in JPQL but HQL has day() and month() functions so you could run:

from User u 
where day(u.birthday) = day(CURRENT_DATE) 
and month(u.birthday) = month(CURRENT_DATE) 

If using HQL is not an option, I would go for a native query.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文