gpt4 book ai didi

java - 如何创建多对多实体的命名查询?

转载 作者:行者123 更新时间:2023-11-29 09:44:57 25 4
gpt4 key购买 nike

品牌

public class Brand implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "BrandID", nullable = false)
private Integer brandID;
@Basic(optional = false)
@Column(name = "BrandName", nullable = false, length = 100)
private String brandName;
@Basic(optional = false)
@Column(name = "Description", nullable = false, length = 1000)
private String description;
@Column(name = "Is_Visible")
private Boolean isVisible;
@JoinTable(name = "brandcategory", joinColumns = {
@JoinColumn(name = "BrandID", referencedColumnName = "BrandID")}, inverseJoinColumns = {
@JoinColumn(name = "CategoryID", referencedColumnName = "CategoryID")})
@ManyToMany(fetch = FetchType.EAGER)
private Collection<Category> categoryCollection;
@OneToMany(mappedBy = "brand", fetch = FetchType.EAGER)
private Collection<Product> productCollection;

我想从表 brandcategory whoes categoryID = :categoryID 中检索品牌 ID我如何在实体品牌中为其创建命名查询?

这不起作用:

@NamedQuery(name = "Brand.getBrandListByCategory",
query = "SELECT b FROM Brand b WHERE b.brandID =
(SELECT bc.brandID
FROM b.brandctegory bc
WHERE bc.category.categoryID = :categoryID)")

最佳答案

如果我没理解错的话,你想要属于一个类别的所有品牌。你为什么不简单地使关联双向。然后你可以这样做:

Category category = em.find(Category.class, categoryId);
return category.getBrands();

如果它是单向的,那么您将需要一个查询,但它比您尝试的查询简单得多:

select b from Brand b inner join b.categoryCollection category 
where category.id = :categoryId;

您的查询没有意义:它使用了一个不存在的关联 (b.brandcategory)。请记住,JPQL 使用实体、它们的持久字段以及与其他实体的关联。没有别的。 JPQL 中不存在表。

关于java - 如何创建多对多实体的命名查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10868809/

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