【发布时间】:2017-07-05 17:45:14
【问题描述】:
我正在尝试使用@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:您的 SQL 中有错误 句法;检查与您的 MariaDB 服务器相对应的手册 在附近使用正确语法的版本 'userprofil0_.YEAR,userprofil0_.BIRTHDATE,CURDATE()) 来自用户)作为 第 1 行的公式 0_0_ f'
如果我在 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 不存在
即使在 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 中执行该查询,只用 YEAR 替换 userprofil0_.YEAR,它工作正常。
【问题讨论】:
-
嗨!我更新了我的答案。你试过了吗?