首页 文章

Hibernate标准为2列之间的差异

提问于
浏览
3

我有一个简单的hibernate实体,有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完成吗?对于这种相当典型的情况,我能不知何故 avoid using SQL/HQL
谢谢!

1 回答

  • 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在Criteria API中指定条件,则可以使用 @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的值是实际的列名而不是映射的属性名 .

相关问题