【问题标题】:How to create a namedquery of manytomany entity?如何创建多对多实体的命名查询?
【发布时间】:2012-06-03 08:08:19
【问题描述】:

品牌

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)")

【问题讨论】:

  • 我没有收到任何错误消息。解决了:)

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


【解决方案1】:

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

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

【讨论】:

  • 谢谢,它成功了。我只是在学习 JPA,所以我犯了那个错误。谢谢。 :)
【解决方案2】:

AFAIK,在实体类中创建查询时,您不能超出实体边界。

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

【讨论】:

  • 当然可以走出实体边界。如果不能,关联将是什么。对于这样一个简单的查询,真的不需要原生查询。
  • @JBNizet,好吧,我并不是这个领域的专家。所以,请忽略我缺乏知识。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多