This my Category Entity
@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;
}
}
And this is my Product entity
@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;
}
}
Now you can see that there is one to many relatonship between category and product.I want to fetch a category with a product id. i wrote a query like
Category c=(Category)session.createQuery("from Category c where c.product.productId=:productId").setParameter("productId",id).list().get(0);
but this query is not working.what did i do wrong in the code.?
I solved it by joining the entity
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.