javax.persistence.criteria.From <?,?>如何使用休眠获取子类字段

时间:2019-08-02 09:25:01

标签: java postgresql hibernate criteria

我下面有两节课:

母班:

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "item_type")
@BatchSize(size = 1000)
@DynamicUpdate(value = true)
@Table(name = "item")
public abstract class Item extends HibernateAbstractEntity {

    @Column(name = "item_type", insertable = false, updatable = false)
    @Enumerated(EnumType.STRING)
    private ItemType type;

    ...
}

儿童班:

@Entity
@DiscriminatorValue("PRODUCT")
public class ItemProduct extends Item {


    @Column(name = "sub_category")
    private String subCategory;

    @Override
    public ItemType getType() {

        return ItemType.PRODUCT;
    }
}

在我的数据库中,我只有一个表,称为包含item.type的Item,而当type == PRODUCT时它也包含item.category

我必须使用休眠条件检索其中category == ?类的PRODUCT类型的所有项目,并且我只能访问From<?, Item> itemFromAbstractQuery<?> criteria

所以我的方法看起来像这样

public void addFilter(From<?, ?> from, AbstractQuery<?> criteria, SearchFilter filter) { 

    Path<?> path = from.get(filter.getProperty()); // here property == 'subCategory'

    Predicate predicate = buildPredicate(criteriaBuilder, path, filter.getOperator(), filter.getValues());

    criteria.where(getCriteriaBuilder().and(criteria.getRestriction(), predicate));

...
}

但是由于我的From<?, Item>是从这里进入的,休眠状态使我出错,告诉我类型item上没有属性subCategory。

我知道这在Java代码中是正确的,但是在数据库中,因为Item和ItemProduct是同一张表,所以它应该工作:/

希望有人遇到同样的问题并愿意提供帮助:)

0 个答案:

没有答案