gpt4 book ai didi

sql - JPA标准API : query property of subclass

转载 作者:行者123 更新时间:2023-12-04 04:35:57 24 4
gpt4 key购买 nike

我有一个这样的类结构:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Article {
private String aBaseProperty;
}

@Entity
public class Book extends Article {
private String title;
}

@Entity
public class CartItem {
@ManyToOne(optional = false)
public Article article;
}

我尝试了以下操作,以接收所有引用了 CartItemsBooktitle = 'Foo':

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<CartItem> query = builder.createQuery(CartItem.class);
Root<CartItem> root = query.from(CartItem.class);
builder.equal(root.get("article").get("title"), "Foo");
List<CartItem> result = em().createQuery(query).getResultList();

但不幸的是,这会导致错误(对我来说很有意义,因为 titleBook中,而不在 Article中……):
java.lang.IllegalArgumentException: Could not resolve attribute named title    at org.hibernate.ejb.criteria.path.SingularAttributePath.locateAttributeInternal(SingularAttributePath.java:101)    at org.hibernate.ejb.criteria.path.AbstractPathImpl.locateAttribute(AbstractPathImpl.java:216)    at org.hibernate.ejb.criteria.path.AbstractPathImpl.get(AbstractPathImpl.java:189)...

However, I was able to achieve what I want using the following HQL:

SELECT c, a FROM CartItem c INNER JOIN c.article a WHERE a.title = ?

那么后者为何起作用,我是否可以使用Criteria API达到类似的目的?

最佳答案

我遇到了同样的问题,并感谢chris(请参阅JPA Criteria API where subclass)找到了解决方案。

为此,您需要JPA 2.1,并使用 CriteriaBuilder.treat() 方法之一。只需将您的builder.equal...行替换为:

builder.equal(builder.treat(root.get("article"), Book.class).get("title"), "Foo");

关于sql - JPA标准API : query property of subclass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6903783/

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