【发布时间】:2017-01-20 23:26:43
【问题描述】:
我与链接表中的额外文件(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
【问题讨论】:
-
请更具体一点:您是否要编写一个查询来返回所有使用具有特定名称的产品的配方?另外:到目前为止,您尝试过什么?
-
我在主要描述中添加了示例
-
我尝试使用 Restrictions.eq("listOfRecipe_Product.id.product.name", "test") 但我收到错误 org.hibernate.QueryException:无法解析属性:listOfRecipe_Product.id.product。名称:食谱
标签: java hibernate criteria hibernate-criteria