Hibernate Formula Annotation - MySql函数:INTERVAL,DAY

时间:2012-04-19 08:02:22

标签: java mysql hibernate annotations

我有代码:

@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的功能?有可能吗?

感谢。

2 个答案:

答案 0 :(得分:0)

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

(now() - INTERVAL 30 DAY)

使用:

DATE_SUB( NOW(), INTERVAL 30 DAY )

答案 1 :(得分:0)

你使用哪种MySQL方言? 如果您可以使用MySqlDialect或MySql5Dialect,请执行以下操作:

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

或者定义新的休眠功能

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)