使用 JPA 查找今天生日的用户
我有一个包含用户的表,并正在尝试获取今天过生日的人的列表,以便应用程序可以发送电子邮件。
用户被定义为
@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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道如何在 JPQL 中执行此操作,但 HQL 有
day()
和month()
函数,因此您可以运行:如果不能使用 HQL,我将进行本机查询。
I don't know how to do that in JPQL but HQL has
day()
andmonth()
functions so you could run:If using HQL is not an option, I would go for a native query.