hibernate里面使用带on条件的left join

来源:互联网 发布:千元空气净化器 知乎 编辑:程序博客网 时间:2024/05/14 13:17

 

来源:http://www.javaeye.com/topic/48537

 

针对信用卡Card的评分Score ,两者的关系是one-to-many. 现在需要查询没有评分过或者评分已经实效的那些卡片。 
在mysql下 
sql: select c.* from card c left join score s on s.card_id = c.id and s.invalid_date >=curdate() where s.id is null 
hibernate中要使用left join必须声明关联映射,这里的关联是one-to-many, 在Card里面建一个Set scores,然后配置好 
        <set name="scores" cascade="none" where="valid_date >= curdate()"> 
              <key column="CARD_ID"/> 
              <one-to-many class="Score" /> 
        </set> 
唯一特殊的就在于这个where,hql里面不能写on ,所以得on里面的条件都写在where里面,where里面是写的是字段名和针对不同数据库的sql,将导致不同数据库之间的移植增加一些工作量。 
hql如下:select c from Card c left join c.scores s  where s.id is null