【问题标题】:Hibernate: query by example and many to one to create listsHibernate:通过示例查询和多对一创建列表
【发布时间】: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


【解决方案1】:

试试这个

FROM product p WHERE p.category.categoryId = :categoryId

【讨论】:

    猜你喜欢
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 2018-11-09
    • 2013-07-13
    • 1970-01-01
    相关资源
    最近更新 更多