gpt4 book ai didi

java - Hibernate 生成不明确的 SQL 查询

转载 作者:行者123 更新时间:2023-11-30 02:36:32 25 4
gpt4 key购买 nike

考虑以下ParentClass实体:

@Entity
@Table(schema = "iwrs")
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class ParentClass {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "PK_IWRS")
public int id;

public String name;

public ParentClass(String name) {
this.name = name;
}
}

以及以下ChildClass实体:

@Entity
@Table(schema = "iwrs")
public class ChildClass extends ParentClass {

@ManyToOne(targetEntity=ParentClass.class)
@JoinColumn(name="parent_id")
private ParentClass parent;

public ChildClass(String name) {
super(name);
}
}

正如你所看到的,这个ChildClass继承自ParentClass。此外,它还包含在 parent 字段中映射的 ParentClass 的引用。

有一点我想获取 ParentClass 的所有实例,但不是 ChildClass 的实例。

我四处搜索,发现可以通过以下标准实现:

Criteria criteria = sessionFactory.getCurrentSession()
.createCriteria(ParentClass.class, "parentClass")
.add(Restrictions.eq("class", ParentClass.class));

但是,当我尝试列出它时,出现以下错误:

ERROR SqlExceptionHelper:147 - ERROR: column reference "clazz_" is ambiguous

如果我删除条件的最后一行,查询将成功执行。但 ChildClass 实例也被返回,这不是我想要的。

这是当我有所有限制时由 hibernate 生成的查询:

select this_.id as id1_29_1_, this_.name as name2_29_1_, this_.parent_id as parent_i1_14_1_, this_.clazz_ as clazz_1_, parentclas2_.id as id1_29_0_, parentclas2_.name as name2_29_0_, parentclas2_.parent_id as parent_i1_14_0_, parentclas2_.clazz_ as clazz_0_ from ( select id, name, null::int4 as parent_id, 0 as clazz_ from iwrs.parent_class union all select id, name, parent_id, 1 as clazz_ from iwrs.child_class ) this_ left outer join ( select id, name, null::int4 as parent_id, 0 as clazz_ from iwrs.parent_class union all select id, name, parent_id, 1 as clazz_ from iwrs.child_class ) parentclas2_ on this_.parent_id=parentclas2_.id where clazz_=?

此处提供工作示例:https://github.com/mmalmeida/hibernateTest ,只需运行测试RetrieveParentTest.java即可。

你知道我该如何解决这个问题吗?

提前致谢!

最佳答案

尝试使用您定义的别名:

Criteria criteria = sessionFactory.getCurrentSession()
.createCriteria(ParentClass.class, "parentClass")
.add(Restrictions.eq("parentClass.class", ParentClass.class));

关于java - Hibernate 生成不明确的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42908492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com