Hibernate Formula Annotation – MySql函数:INTERVAL,DAY

我有代码:

@Id @Column(name = "id") @GeneratedValue private int id; @Formula(value = "(SELECT count(history.city_id) FROM history where history.ts > (now() - INTERVAL 30 DAY) and history.city_id = id)") private int last30daysUpdates; 

所以,hiberante将这个公式解析为:

  ...where history.ts > ( now() - entitycity0_.INTERVAL 30 entitycity0_.DAY ) ... 

而错误是:

您的SQL语法有错误; 查看与您的MySQL服务器版本对应的手册,以便在’30 entitycity0_.DAY附近使用正确的语法

我怎么说hibernate INTERVAL和DAY是MysqL的function? 可能吗?

谢谢。

您使用哪种MySQL方言? 如果MySqlDialect或者MySql5Dialect你可以使用如下:

 SELECT count(history.city_id) FROM history where timediff(now(), history.ts) < '720' and history.city_id = id 

或者定义新的hibernatefunction

 public class ExtendedMySQL5Dialect extends MySQL5Dialect { public ExtendedMySQL5Dialect() { super(); registerFunction( "date_sub_interval", new SQLFunctionTemplate( Hibernate.DATE, "date_sub(?1, INTERVAL ?2 ?3)" ) ); registerFunction( "date_add_interval", new SQLFunctionTemplate( Hibernate.DATE, "date_add(?1, INTERVAL ?2 ?3)" ) ); } } 

查询:

 History.ts < date_sub_interval(now(), 30, DAY) 

INTREVALDAY (这里使用的)不是函数。 不确定Hibernate是否“被说服”但你可以尝试替换:

 (now() - INTERVAL 30 DAY) 

有:

 DATE_SUB( NOW(), INTERVAL 30 DAY )