gpt4 book ai didi

hibernate - 如何使用 JPA CriteriaQuery 搜索子类属性?

转载 作者:行者123 更新时间:2023-12-03 13:01:54 24 4
gpt4 key购买 nike

我正在尝试编写一个查询来搜索不在其父类(super class)中的子类属性并返回父类(super class)的所有对象。目前,当我尝试执行 person.get("specialAttribute") 时,我收到了 NullPointerException。

@Inheritance(strategy = InheritanceType.JOINED)
@Entity
public abstract class Person {
public String searchableAttribute;
}

@Entity
@Table( name = "normal_person" )
public class NormalPerson extends Person {

}

@Entity
@Table( name = "special_person" )
public class SpecialPerson extends Person {
@Column(nullable = false, unique = true)
public String specialAttribute;
}

// Controller method

Root<Person> person = query.from(Person.class);
query.where(
builder.or(
builder.like(person.<String>get("specialAttribute"), "foo"),
builder.like(person.<String>get("searchableAttribute"), "foo")
)
);

最佳答案

按照提供的提示解决了我自己的问题 here .

Root<Person> person = query.from(Person.class);

Subquery<SpecialPerson> subQuery = query.subquery(SpecialPerson.class);
Root<SpecialPerson> specialPersonRoot = subQuery.from(SpecialPerson.class);

subQuery.select(specialPersonRoot);
subQuery.where(builder.like(specialPersonRoot.<String>get("specialAttribute"), "foo"));

query.where(
builder.or(
builder.in(person).value(subQuery)
builder.like(person.<String>get("searchableAttribute"), "foo")
)
);

关于hibernate - 如何使用 JPA CriteriaQuery 搜索子类属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9875943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com