Запрос API JPA Criteria по свойству подкласса - PullRequest
0 голосов
/ 30 апреля 2020

Я пытаюсь выполнить запрос по свойству в подклассе со следующей структурой:

@Entity
@Table(name = "base_entity")
public class BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected Long id;

    protected String field1;

    // Getters & Setters
}

@Entity
@DiscriminatorValue(value = "SUB_ONE")
public class SubEntity extends BaseEntity {

    private String subfield;

    // Getters & Setters
}

@Entity
@Table(name = "another_entity")
public class AnotherEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected Long id;

    @ManyToOne
    private BaseEntity baseEntity;

    // Getters & Setters
}

У меня есть эта спецификация критериев:

public class AnotherEntitySpecification implements Specification<AnotherEntity> {

    @Override
    public Predicate toPredicate(Root<AnotherEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

        Join join = root.join("baseEntity");
        return cb.like(join.get("subfield"), "value");
    }
}

Я получил это ошибка, поскольку JPA выполняет поиск подполя в BaseEntity:

Caused by: java.lang.IllegalArgumentException: Unable to locate Attribute  with the the given name [subfield] on this ManagedType [com.foo.test.BaseEntity]

Я пробовал с лечить , и это работает, но создает дополнительные объединения и смотрит вокруг.

Join<AnotherEntity, SubEntity> join = root.join("baseEntity");
Join<AnotherEntity, SubEntity> treat = cb.treat(join, SubEntity.class);
return cb.like(treat.get("subfield"), "value");
select anotherent0_.id as id1_0_, anotherent0_.base_entity_id as base_ent2_0_ 
    from another_entity anotherent0_ 
    inner join base_entity baseentity1_ on anotherent0_.base_entity_id=baseentity1_.id 
    inner join base_entity baseentity2_ on anotherent0_.base_entity_id=baseentity2_.id 
    where baseentity2_.subfield like ?

Возможно ли любое приведение (BaseEntity -> SubEntity) или запрос по «подполю», и нет проверки, существует ли BaseEntity?

...