SQL 查询中的 Hibernate ManyToOne 关联和连接表

标签 hibernate criteria inner-join many-to-one

我有关于 Hibernate ManyToOne 关联的问题。

我有一个像这样映射的产品实体:

public class Product {
@Id
@DocumentId
@Column(name = "PRODUCT_ID", columnDefinition = "integer")
@Index(name = "PRODUCT_ID_IDX")
private Long id;

@Column(name = "SALE_PRICE")
@Index(name = "PRODUCT_PRICE_IDX")
private Double salePrice;
...
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "CATEGORY_ID", nullable = true)
@Index(name = "PRODUCT_ID_CATEGORY_IDX")
private ProductCategory category;
}

那么你怎么能看到我们与 ProductCategory 表有关系呢?我们将 FK 存储在 Product 表中。 当我创建按特定类别和价格选择产品的查询时,我有下一个 SQL: select this_.PRODUCT_ID as PRODUCT1_9_1_, this_.BUY_URL as BUY2_9_1_, this_.CATEGORY_ID as CATEGORY15_9_1_, this_.CURRENCY as CURRENCY9_1_, this_.IMAGE_URL as IMAGE4_9_1_, this_.INSTOCK as INSTOCK9_1_, this_.LONG_DESCRIPTION as LONG6_9_1_, this_.NAME as NAME9_1_, this_.RATING as RATING9_1_, this_.RETAIL_PRICE as RETAIL9_9_1_, this_.SALE_PRICE as SALE10_9_1_, this_.SHIPPING as SHIPPING9_1_, this_.SHORT_DESCRIPTION as SHORT12_9_1_, this_.UPC as UPC9_1_, this_.VIEWS as VIEWS9_1_, cat1_.CATEGORY_ID as CATEGORY1_10_0_, cat1_.NAME as NAME10_0_, cat1_.RATING as RATING10_0_, cat1_.VIEWS as VIEWS10_0_, cat1_.VISIBLE as VISIBLE10_0_ from PRODUCT this_ inner join PRODUCT_CATEGORY cat1_ on this_.CATEGORY_ID=cat1_.CATEGORY_ID where ( this_.SALE_PRICE between ? and ? and cat1_.CATEGORY_ID in ( ? ) ) order by this_.NAME asc limit ? offset ?

我的下一个问题是:如何避免两个表的内部联接:Product 和 ProductCategory?

我的 Criteria DAO 代码: criteria.createAlias("category", "cat"); criteria.add(Restrictions.conjunction() .add(Restrictions.between("salePrice", priceLow, priceHigh)) .add(Restrictions.in("cat.id", categoryIds)));

谢谢。

最佳答案

线路

criteria.createAlias("category", "cat");

准确的意思是:创建与 Category 实体的内部联接。

直接使用

criteria.add(
    Restrictions.conjunction()
        .add(Restrictions.between("salePrice", priceLow, priceHigh))
        .add(Restrictions.in("category.id", categoryIds)));

关于SQL 查询中的 Hibernate ManyToOne 关联和连接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11395662/

相关文章:

java - hibernate 标准 API : how to get the sum of all the values along two columns

php - SQL 查询后跟内连接

sql - 在 2 表中请求 SQL

java - 更新数据库列后检索它的值

java - Hibernate 初始化期间 Joda 类型 def 加载失败

java - hibernate 列表

Hibernate——条件与命名查询

hibernate - Spring:尚未配置事务管理器

grails - 如何在grails中将if语句放入createCriteria中?

Mysql Update column with percentage from other tables