【问题标题】:Hibernate criteria for difference between 2 columns两列之间差异的休眠标准
【发布时间】:2012-03-05 17:12:18
【问题描述】:

我有一个简单的休眠实体,有 2 个字段 - ab:

@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
谢谢!

【问题讨论】:

    标签: java hibernate criteria


    【解决方案1】:

    您可以使用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) &gt; 5

    如果您不想在 Criteria API 中使用 SQL 来指定条件,您可以使用 @Formula 将 (a - b) 定义为派生属性:

    @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 的值是实际的列名而不是映射的属性名。

    【讨论】:

    • 谢谢肯。但正如我在一个问题中提到的,我试图避免使用 SQL/HQL。
    猜你喜欢
    • 1970-01-01
    • 2021-10-19
    • 2020-03-13
    • 1970-01-01
    • 2014-04-23
    • 2021-03-17
    • 2016-09-23
    • 1970-01-01
    • 2016-05-24
    相关资源
    最近更新 更多