hibernate mysql annotation,Hibernate Formula Annotation - MySql函数:INTERVAL,DAY

博客讨论了在Hibernate中使用@Formula注解时遇到的SQL语法错误,问题在于尝试使用MySQL的INTERVAL和DAY函数。作者提出了两种解决方案:一是改用timediff函数,二是自定义Hibernate函数。通过这两种方式可以解决 Hibernate 对MySQL特定函数解析的问题。
摘要由CSDN通过智能技术生成

I have the code:

@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;

so, hiberante parse this formula to:

...where

history.ts > (

now() - entitycity0_.INTERVAL 30 entitycity0_.DAY

) ...

and the error is:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '30 entitycity0_.DAY)

How can i say hibernate that INTERVAL and DAY are the functions of MysqL? Is it possible?

Thanks.

解决方案

Which MySQL dialect are you use?

If MySqlDialect oder MySql5Dialect you can use follows:

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

Or define new hibernate function

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)" ) );

}

}

Query:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值