这是我的类别实体
@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);
但是这个查询不起作用。我在代码中做错了什么。?
答案 0 :(得分:0)
我通过加入实体来解决它
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);