Hibernate One-To-Many匹配多个ID

时间:2015-03-03 10:17:43

标签: java hibernate one-to-many

我正在使用Hibernate 4和JSF 2.

给出以下映射

@Entity
@Table(name = "feature")
public class Feature 
{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column
    private String name;

}

@Entity
@Table(name = "product")
public class Product
{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column
    private String name;

    @OneToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "product_feature", joinColumns = @JoinColumn(name = "product_id"), inverseJoinColumns = @JoinColumn(name = "feature_id"))
    private Set<Feature> features = new HashSet<Feature>(0);

}

数据库结构

Product
---------
id
name

Feature
---------
id
name

Product_Feature
----------------
product_id
feature_id

我现在要做的是,构建一个DetachedCriteria来获取所有产品,让我们说出功能1,2和3.不仅仅是其中一个,而是所有产品。

我无法获得正确的限制,找到符合所有特定功能的产品,而不仅仅是一个。

DetachedCriteria criteria = DetachedCriteria.for(Product.class, "product");
criteria.createAlias("product.features", "feature");

我很感激任何帮助。提前谢谢。

1 个答案:

答案 0 :(得分:0)

我通过添加以下sql限制来修复它。

String features = "1,4,5";
int featureSize = 3;

DetachedCriteria criteria = DetachedCriteria.for(Product.class, "product");

criteria.add(Restrictions.sqlRestriction(String.format("(SELECT COUNT(*) FROM product_feature pf where pf.feature_id in(%s) and pf.product_id={alias}.id)=%d", features, featureSize)));

这确保了产品具有所有三个功能,而不仅仅是一个或两个。