具有单表继承的子类的JPA查询

时间:2015-01-08 14:19:23

标签: java java-ee jpa criteria-api java-ee-7

说我有以下实体:

@Entity
public class Container
{
    @OneToMany
    Set<AbstractElement> elements;

    //getter setter and other attributes...
}

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "CLASS_CODE", discriminatorType = DiscriminatorType.STRING, length = 10)
public abstract class AbstractElement<T> extends AbstractEntity
{
    @Transient
    T value;

    //getter setter and other attributes...
}

@DiscriminatorValue(value = "BOOL")
@Entity
public class BooleanElement extends AbstractElement<Boolean>
{
    /**
     * {@inheritDoc}
     */
    @Column(name = "VALUE_BOOL")
    @Override
    public Boolean getValue()
    {
        return super.getValue();
    }
}

问题是:

如何从类CONTAINER开始对BooleanElement的值执行jpa条件查询?

到目前为止我实际拥有的是:

CriteriaQuery<Container> criteriaQuery = criteriaBuilder.createQuery(Container.class);
Root<Container> from = criteriaQuery.from(Container.class);
criteriaQuery.select(from);
from = from.join("elements");
Predicate pred = criteriaBuilder.equal(criteriaBuilder.treat(from ,BooleanElement.class).get("value"), FOO);

//etc......

此时的例外情况是“AbstractEntity上没有VALUE属性”。

提前致谢。

1 个答案:

答案 0 :(得分:0)

在这种特定情况下,Treat运算符不起作用。 加入时的as运算符仍然不太清楚如何实现:在执行此操作时,我在第3行获得了类转换异常:

CriteriaQuery<AbstractElement> criteriaQuery = criteriaBuilder.createQuery(AbstractElement.class);
Root<AbstractElement> rootAbstract = criteriaQuery.from(AbstractElement.class);
Path predPath = (Path)rootAbstract.as(BooleanElement.class);
predPath.get("value");

执行此类查询的唯一方法是执行子查询 或者创建一个额外的“from”子句:

Root<BooleanElement> from2 = criteriaQuery.from(BooleanElement.class);
Predicate joinPredicate = criteriaBuilder.equal(from, from2);
....