当前位置:  开发笔记 > 数据库 > 正文

将SQL转换为HQL

如何解决《将SQL转换为HQL》经验,为你挑选了1个好方法。

我正在尝试将以下SQL查询转换为HQL,并且遇到了一些问题.直线逐行转换不起作用,我想知道我是否应该在HQL中使用内部联接?

        SELECT (UNIX_TIMESTAMP(cosc1.change_date) - UNIX_TIMESTAMP(cosc2.change_date)) 
        FROM customer_order_state_change cosc1  
        LEFT JOIN customer_order_state cos1_new on cosc1.new_state_id = cos1_new.customer_order_state_id  
        LEFT JOIN customer_order_state cos1_old on cosc1.old_state_id = cos1_old.customer_order_state_id  
        LEFT JOIN customer_order_state_change cosc2 on cosc2.customer_order_id = cosc1.customer_order_id  
        LEFT JOIN customer_order_state cos2_new on cosc2.new_state_id = cos2_new.customer_order_state_id  
        LEFT JOIN customer_order_state cos2_old on cosc2.old_state_id = cos2_old.customer_order_state_id 
        WHERE cos1_new.name = "state1" AND  cos2_new.name = "state2" and cosc2.change_date < "2008-11-06 09:00" 
AND cosc2.change_date > "2008-11-06 06:00" GROUP BY cosc1.change_date, cosc2.change_date ;

查询返回客户订单状态更改之间的时间(以秒为单位).

状态名称和日期将动态插入到查询中.

编辑:刚试过这个

"SELECT (UNIX_TIMESTAMP(cosc1.changeDate) - UNIX_TIMESTAMP(cosc2.changeDate))" + 
        " FROM" + 
        " " + CustomerOrderStateChange.class.getName() + " as cosc1" +
        " INNER JOIN " + CustomerOrderStateChange.class.getName() +  " as cosc2" +
        " WHERE cosc1.newState.name = ?" +
        " AND cosc1.order.id = cosc2.order.id" + 
        " AND cosc2.newState.name = ?" +
        " AND cosc2.changeDate < ?" +
        " AND cosc2.changeDate > ?" + 
        " GROUP BY cosc1.changeDate, cosc2.changeDate";

并收到异常" 外部或完全连接必须后跟路径表达式 "



1> 小智..:

通常,您使用对象上的属性指定HQL连接,例如,如果类Foo和Bar和Foo.bar的类型为Bar,from Foo f inner join f.bar as b则为连接.据我所知,没有办法在HQL中执行自联接(我可能在这里错了).

也就是说,Hibernate允许您编写(略微增强的)SQL查询session.createSQLQuery(...).

推荐阅读
帆侮听我悄悄说星星
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有