Hibernate标准为2列之间的差异

Sto*_*orm 3 java hibernate criteria

我有一个简单的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;
}
Run Code Online (Sandbox Code Playgroud)


我需要选择所有球员在哪里a - b > 5.
可以使用标准的Hibernate Criteria API完成吗?我可以以某种方式避免使用SQL/HQL来处理这种相当典型的情况吗?
谢谢!

Ken*_*han 8

您可以使用Restrictions.sqlRestriction()生成Criterion使用SQL条件:

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

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

如果您不想使用SQL在Criteria 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();
Run Code Online (Sandbox Code Playgroud)

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