【发布时间】:2021-12-29 00:31:49
【问题描述】:
假设这些是我的实体:
Product.java
@Entity
@Table(name = "Products")
public class Product{
private int code;
private String name;
private double price;
private byte[] image;
private String image1;
// For sort.
private Date createDate;
@ManyToOne
@JoinColumn(name = "categoryId")
private Category category;
}
Category.java
@Entity
@Table(name = "Categorys")
public class Category {
@Id
@GeneratedValue
private int categoryId;
private String categoryName;
private String categoryUrl;
@Column(name = "categoryStatus", length = 1, nullable = false)
private boolean categoryStatus;
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "categoryId")
private List<Product> listProduct;
}
我想按类别 ID 列出所有行产品。但我不知道如何通过 Hibernate 查询 这是我正在使用的示例工具,但它不起作用。 有人请帮帮我
@Override
public List<Product> getListByCategory(int categoryId) {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("FROM product WHERE categoryId = categoryId");
query.setLong("categoryId", categoryId);
List<Product> list = query.list();
return list;
}
【问题讨论】:
-
FROM product WHERE category.categoryId=:categoryId应该可以工作。请注意对category的附加引用(Product中的属性名称)和附加的:以记下参数的名称。所有这些都包含在基本的 HQL 查询教程中,因此您可能需要阅读它。
标签: java spring hibernate spring-mvc