我是JPA的新手,我很难写我的查询。 我需要计算和过滤不属于我的实体的列(状态标志取决于请求的日期参数)
这是我简化的测试实体:
@Entity
@Table(name = "test")
public class TestEntity implements Serializable, Identifiable<Long> {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "test_seq")
@SequenceGenerator(name = "test_seq", sequenceName = "test_seq", allocationSize = 1)
@Column
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private ZonedDateTime date;
}
现在我的测试查询:
// simple query, with my computed status => WORKS
query = entityManager.createQuery("SELECT e.name, e.date, "
+ " CASE WHEN :date < e.date THEN 1 ELSE 0 END"
+ " FROM " + TestEntity.class.getName() + " e");
// simple query with ORDER clause => WORKS
query = entityManager.createQuery("SELECT e.name, e.date, "
+ " (CASE WHEN :date < e.date THEN 1 ELSE 0 END) AS status"
+ " FROM " + TestEntity.class.getName() + " e"
+ " ORDER BY status");
// add 'where' close => KO: 'user lacks privilege or object not found: STATUS in statement'
query = entityManager.createQuery("SELECT e.name, e.date, "
+ " (CASE WHEN :date < e.date THEN 1 ELSE 0 END) AS status"
+ " FROM " + TestEntity.class.getName() + " e"
+ " WHERE status = 1");
// SubQuery in FROM clause => KO: unexpected token: ( near line 1, column 19
query = entityManager.createQuery("SELECT proj FROM "
+ " (SELECT e.name, e.date, "
+ " (CASE WHEN :date < e.date THEN 1 ELSE 0 END) AS status"
+ " FROM " + TestEntity.class.getName() + " e) proj"
+ " WHERE proj.status = 1");
如果有人可以提供帮助;) 感谢
更新1:
// a more representative query, where status(:time) is an heavy CASE
// statement with a:time parameter and multiplle return values
"SELECT e.name, e.date, status(:time) "
+ " FROM " + TestEntity.class.getName() + " e"
+ " WHERE (SELECT status(:time) FROM TestEntity.class) IN :filtered"
+ " AND e.name IN :filteredName"
这是我成功的最佳工作解决方案,但它需要双重状态计算。 我在文档上找不到更好的东西,也没有google。