我正在尝试使用 @Formula
根据用户的出生日期计算她的年龄。
根据MySQL documentation ,我已经尝试过:
@Entity
@Table(name = "users")
public final class UserProfile {
//this column is called BIRTHDATE in database
private String birthdate;
@Formula("(select TIMESTAMPDIFF(YEAR,BIRTHDATE,CURDATE()) from users)")
private String age;
//more things...
}
但是我收到一个错误:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'userprofil0_.YEAR,userprofil0_.BIRTHDATE,CURDATE()) from users) as formula0_0_ f' at line 1
如果我在 phpMyAdmin 中执行该查询,它就会正常工作。
已关注 this ,我也尝试过:
@Formula("date_part('year', age(birthdate))")
private String age; //I tried with int instead of String, too
但是我有这个错误:
java.sql.SQLSyntaxErrorException: FUNCTION userprofile-service-db.date_part does not exist
这个即使在 phpMyAdmin 中也不起作用...
有什么想法吗?
编辑
我刚刚尝试过:
@Formula("(TIMESTAMPDIFF(YEAR,BIRTHDATE,CURDATE()))")
private String age;
但仍然无法正常工作。这是 Hibernate 显示的查询:
select
userprofil0_.id as id1_1_0_,
userprofil0_.about_me as about_me2_1_0_,
userprofil0_.birthdate as birthdat3_1_0_,
userprofil0_.display_name as display_4_1_0_,
userprofil0_.email as email5_1_0_,
userprofil0_.profile_photo as profile_6_1_0_,
(TIMESTAMPDIFF(userprofil0_.YEAR,
userprofil0_.BIRTHDATE,
CURDATE())) as formula0_0_
from
users userprofil0_
where
userprofil0_.id=?
看起来 Hibernate 将 YEAR
作为列,但实际上它是一个保留字。如果我在 phpMyAdmin 中执行该查询,将 userprofil0_.YEAR
替换为 YEAR
,它就可以正常工作。
最佳答案
您的第一次尝试几乎是正确的,但您不需要 select
和 from
部分,因为列 BITHDATE
位于同一个表中:
@Formula("(TIMESTAMPDIFF(YEAR,BIRTHDATE,CURDATE()))")
private String age;
打开生成的 SQL 查询的日志记录也很有用(在 Hibernate 中,这是通过将属性 show_sql
设置为 true
来完成的),以查看整个查询。
更新
作为 Hibernate 将 YEAR
视为列名的解决方法,您可以将对 TIMESTAMPDIFF
的调用包装在自定义 MySQL 函数中,并在 Formula 中调用此函数。这是SOanswer类似的问题。
另一个解决方案可能是编写一个自定义方言解析器,它将 YEAR 视为关键字:SO answer
关于java - 使用@Formula从出生日期计算年龄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44932828/