2012-03-05 187 views
3

之间的区别我有2场一个微不足道的休眠实体 - ab
休眠标准2列

@Entity 
public class PlayerEntity { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Integer id; 

    @Column(nullable = false) 
    private Integer a; 

    @Column(nullable = false) 
    private Integer b; 
} 


我需要选择所有的球员在那里a - b > 5
这可以使用标准的Hibernate Criteria API完成吗?我可以不知何故避免使用SQL/HQL这种相当典型的情况?
谢谢!

回答

8

可以使用Restrictions.sqlRestriction()使用SQL条件产生Criterion

List<PlayerEntity> playerList = (List<PlayerEntity>)session.createCriteria(PlayerEntity.class) 
.add(Restrictions.sqlRestriction("(a- b) > 5")).list(); 

这将生成SQL:select * from PlayerEntity where (a-b) > 5

如果你不想使用SQL在指定条件标准API,你可以定义(A - b)为使用@Formula派生属性:

@Entity 
public class PlayerEntity { 

    @Column(nullable = false) 
    private Integer a; 

    @Column(nullable = false) 
    private Integer b; 

    @Formula("a - b") 
    private Integer delta 
} 

List<PlayerEntity> playerList = (List<PlayerEntity>)session.createCriteria(PlayerEntity.class) 
.add(Restrictions.gt("delta", 5).list(); 

请注意@Formula的值是实际的列名称而不是映射的属性名称。

+0

谢谢Ken。但正如我在一个问题中提到的,我试图避免使用SQL/HQL。 – Storm 2012-03-05 17:45:41

+0

查看我的最新plz – 2012-03-06 02:23:03