I have a trivial hibernate entity with 2 fields – a and b:
@Entity
public class PlayerEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(nullable = false)
private Integer a;
@Column(nullable = false)
private Integer b;
}
I need to select all the players where a - b > 5.
Can this be ever done using standard Hibernate Criteria API? Can I somehow avoid using SQL/HQL for this rather typical condition?
Thanks!
You can use Restrictions.sqlRestriction() to produce a
Criterionusing a SQL condition:which will generate the SQL :
select * from PlayerEntity where (a-b) > 5If you don’t want to use the SQL to specify condition in the Criteria API ,you can define (a – b) as the derived property using the
@Formula:Please note that the value of @Formula is the actual column name instead of the mapped property names.