小编典典

Hibernate公式注释-MySql函数:INTERVAL,DAY

hibernate

我有代码:

@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服务器版本相对应的手册以获取正确的语法,以在‘30Entitycity0_.DAY附近使用)

我怎样说hibernate和间隔是MysqL的功能?可能吗?

谢谢。


阅读 621

收藏
2020-06-20

共1个答案

小编典典

您使用哪种MySQL语言?如果使用MySqlDialect或MySql5Dialect,则可以使用以下命令:

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

或定义新的hibernate功能

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)
2020-06-20