[英]How to create a namedquery of manytomany entity?
牌
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中不存在表。
AFAIK,在實體類中創建查詢時,您不能超出實體邊界。
而是使用實體管理器的.createNativeQuery()
方法來創建復雜的混合查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.