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

时间:2012-07-09 13:06:22

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

我对Hibernate ManyToOne关联有疑问。

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

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?

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

感谢。

1 个答案:

答案 0 :(得分:2)

该行

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

正是指:使用Category实体创建内部联接。

只需使用

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