我正在使用 hibernate 来实现应用程序中的实体持久性,但是当我使用 HQL 来获取实体时,它工作正常并返回表中实体的确切数量,但是当我在示例中使用 hibernate 的标准时,它会返回第一个实体两次从而导致返回的实体比表中实际存在的实体多
实体定义
public class ItemParentCategory {
@Id
@GeneratedValue
private long id;
private String name;
@OneToMany(mappedBy = "itemParentCategory",fetch = FetchType.EAGER)
@JsonIgnore
private List<ItemSubCategory> itemSubCategorys;
@OneToOne
private ItemMainCategory itemMainCategory;
@JsonIgnore
private String summary;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<ItemSubCategory> getItemSubCategorys() {
return itemSubCategorys;
}
public void setItemSubCategorys(List<ItemSubCategory> itemSubCategorys) {
this.itemSubCategorys = itemSubCategorys;
}
public ItemMainCategory getItemMainCategory() {
return itemMainCategory;
}
public void setItemMainCategory(ItemMainCategory itemMainCategory) {
this.itemMainCategory = itemMainCategory;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
}
获取实体的代码
@Override
public List<ItemParentCategory> getAllItemParentCategoryUnderItemMainCategory(long itemMainCategoryId) {
//This code works fine
Query query = sessionFactory.getCurrentSession().getNamedQuery("ItemParentCategory.getAllItemParentCategoryUnderItemMaincategory");
query.setParameter("itemMainCategoryId", itemMainCategoryId);
return query.list();
//This Code return undesired result
/*Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ItemParentCategory.class);
ItemParentCategory itemParentCategory = new ItemParentCategory();
ItemMainCategory itemMainCategory = new ItemMainCategory();
itemMainCategory.setId(itemMainCategoryId);
itemParentCategory.setItemMainCategory(itemMainCategory);
Example example = Example.create(itemParentCategory);
criteria.add(example);
return criteria.list();*/
}
我使用的HQL
FROM ItemParentCategory itemParentCategory WHERE itemParentCategory.itemMainCategory.id = :itemMainCategoryId
最佳答案
此处发生的情况是由于您已将 ItemParentCategory 作为 FetchType.EAGER 映射到 ItemSubcategory。
现在,这不会影响您的 HQL 查询,因为 HQL 查询不会遵循 EAGER 映射,并且要急于获取 HQL 中的子类别,您必须在查询中显式定义 FETCH JOIN。因此,在这种情况下一切都很好。
如果您将 HQL 更改为如下所示,您大多数都会遇到相同的重复问题:
从 ItemParentCategory ipc JOIN FETCH ipc.itemSubCategorys WHERE ipc.itemMainCategory.id = :itemMainCategoryId
请参阅以下两个常见问题解答:
HQL queries always ignore the setting for outer-join or fetch="join" defined in mapping metadata. This setting applies only to associations fetched using get() or load(), Criteria queries, and graph navigation
示例查询必须以与标准查询类似的方式工作,并且您有 fetch = FetchType.EAGER
Hibernate 正在执行显式连接。您应该打开 SQL 日志记录以查看每种情况下生成的实际 SQL。
关于java - Hibernate 的 Criteria With Examples 和 Query 返回不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28748904/