如何创建manytomany实体的命名查询?

时间:2012-06-03 08:08:20

标签: java jpa many-to-many named-query

品牌

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;

我想从table brandcategory中检索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)")

2 个答案:

答案 0 :(得分:12)

如果我理解正确,您希望所有品牌属于某个类别。为什么不简单地使关联双向。然后你可以这样做:

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中不存在表。

答案 1 :(得分:0)

AFAIK,在实体类中创建查询时,你无法走出实体边界。

而是使用实体管理器的.createNativeQuery()方法来创建复杂和混合查询。