首页 文章

Hibernate Criteria API where子句中的多对多关系

提问于
浏览
1

在链接表中使用额外的文件(在xml文件中映射),我有很多关系 . 使用标准api如何为产品名称添加限制?

public class Recipe implements Serializable{

    private int id_re;

    private String name;

    private Set<ProductRecipe> listOfRecipe_Product = new HashSet<>(0);
}


public class ProductRecipe implements Serializable{

    private ProductRecipeMapping id;

    private float quantity;
}

public class ProductRecipeMapping implements Serializable{

    private Product product;

    private Recipe recipe;
}

public class Product implements Serializable{

    private int id_p;

    private String name;
}

制图:

<class entity-name="recipe" name="Recipe" table="recipe">
        <id name="id_re" type="java.lang.Integer">
            <column name="id_re" />
            <generator class="identity" />
        </id>
        <set name="listOfRecipe_Product" table="recipe_product" lazy="false" fetch="select" cascade="all">
            <key>
                <column name="id_re" not-null="true" />
            </key>

            <one-to-many entity-name="productRecipe" />
        </set>
</class>

<class entity-name="productRecipe" name="ProductRecipe" table="recipe_product">
        <composite-id name="id" class="ProductRecipeMapping" >
            <key-many-to-one name="recipe" entity-name="recipe" column="id_re" />
            <key-many-to-one name="product" entity-name="product" column="id_p" />
        </composite-id>

        <property name="quantity" type="float" column="quantity" />

</class>    

<class entity-name="product" name="Product" table="product">

        <id name="id_p" type="java.lang.Integer" column="id_p">
            <generator class="identity" />
        </id>

        <property name="name" column="name" type="java.lang.String" not-null="true" length="255"/>

</class>

例如 . 我使用标准获取配方名称测试:

Criteria cr = session.createCriteria(Recipe.class);
cr.add(Restrictions.eq("name", "test"));

但我不知道所有食谱的列表名称都是cr.add(Restrictions.eq(“product.name”,“test”)); (但没有工作)

我使用2个想法来解决这个问题,但没有任何效果:

1) Restrictions.eq("listOfRecipe_Product.id.product.name", "test") 但我收到错误 org.hibernate.QueryException: could not resolve property: listOfRecipe_Product.id.product.name of: recipe

2)

cr.createCriteria("listOfRecipe_Product")
    .createCriteria("id")
    .createCriteria("product")
    .add(Restrictions.eq("name", "test"));

我收到错误 org.hibernate.QueryException: Criteria objects cannot be created directly on components. Create a criteria on owning entity and use a dotted property to access component property: listOfRecipe_Product.id

1 回答

  • 0

    您需要创建别名才能向映射实体添加约束;

    例如 . :

    Criteria cr = session.createCriteria(Recipe.class)
      .createAlias("listOfRecipe_Product", "listOfRecipe_Product")
      .createAlias("listOfRecipe_Product.id", "id")
      .createAlias("id.product", "product")
      .add(Restrictions.eq("product.name", "test"));
    

相关问题