【问题标题】:hql query for one to many relationshiphql查询一对多关系
【发布时间】:2015-03-31 03:01:35
【问题描述】:

这是我的类别实体

@Entity
public class Category {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@OneToMany(mappedBy = "category",cascade = CascadeType.ALL)
List<Product>product;

public Category(){

}


public Category(int id){

    this.id=id;
}

public Category(String name){
    this.name=name;
}
public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public List<Product> getProduct() {
    return product;
}

public void setProduct(List<Product> product) {
    this.product = product;
}


private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
 }

}

这是我的产品实体

@Entity
public class Product implements java.io.Serializable  {

@ManyToOne(fetch = FetchType.EAGER)
private Category category;

public Category getCategory() {
    return category;
}

public void setCategory(Category category) {
    this.category = category;
}


@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int productId;

public int getProductId() {
    return productId;
}

public void setProductId(int productId) {
    this.productId = productId;
}


@NotEmpty
private String name;
@NotEmpty
private int price;



public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

 public int getPrice() {
    return price;
 }

public void setPrice(int price) {
    this.price = price;
 }

 }

现在您可以看到类别和产品之间存在一对多的关系。我想获取具有产品 ID 的类别。我写了一个类似

的查询
 Category c=(Category)session.createQuery("from Category c where    c.product.productId=:productId").setParameter("productId",id).list().get(0);

但是这个查询不起作用。我在代码中做错了什么?

【问题讨论】:

  • 不工作是什么意思?您遇到了什么错误?
  • 非法尝试使用元素属性引用 [productId] [来自 com.domain.Category c where c.product.productId=:productId] 取消引用集合 [category0_.id.product]

标签: hibernate hql


【解决方案1】:

我通过加入实体解决了

Category c=(Category)session.createQuery(
    "select c from Category as c " +
    "inner join c.product as product " +
    "where product.productId=:productId"
).setParameter("productId",id).list().get(0);

【讨论】:

    猜你喜欢
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 2014-09-03
    • 2016-09-01
    • 2012-09-06
    • 1970-01-01
    • 2018-01-26
    相关资源
    最近更新 更多