【发布时间】:2014-10-26 19:12:05
【问题描述】:
假设我有以下实体:
@Entity
@Inheritance(strategy = SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
public abstract class BaseEntity {
private Date someDate;
private Date otherDate;
private boolean flag;
}
@Entity
@DiscriminatorValue("entity1")
public class Entity1 extends BaseEntity {
private String someProperty;
}
@Entity
@DiscriminatorValue("entity2")
public class Entity2 extends BaseEntity {
private String otherProperty;
}
我正在尝试构建一个条件查询,该查询根据 BaseEntity 和两个子类中的属性返回 BaseEntity 的实例。所以本质上我正在寻找一个对应于这个伪 SQL 的条件查询:
SELECT * FROM <BaseEntity table name>
WHERE someDate < ? AND otherDate > ? AND flag = ?
AND someProperty = ? AND otherProperty = ?;
我宁愿不构建两个单独的查询,因为它们有太多重叠(即大多数属性都在基类中)。但是,如果我将 BaseEntity 声明为根,我还没有找到在查询中引用子类属性的方法。是否可以构建这样的条件查询?
更新:
也许一些代码可以澄清这个问题。我基本上想做这样的事情:
CriteriaBuilder builder = ...;
CriteriaQuery<BaseEntity> query = ...;
Root<BaseEntity> root = ...;
query.select(root).where(builder.and(
builder.lessThan(root.get(BaseEntity_.someDate), new Date()),
builder.greaterThan(root.get(BaseEntity_.otherDate), new Date()),
builder.isTrue(root.get(BaseEntity_.flag)),
builder.equal(root.get(Entity1_.someProperty), "foo"), <-- This won't work
builder.equal(root.get(Entity2_.otherProperty), "bar") <-- Neither will this
));
现在,我明白为什么上面的代码示例不起作用了,但我想知道是否有办法绕过它。
【问题讨论】:
标签: java jpa criteria-api