2017-03-20 89 views
1

考虑以下父类实体:休眠产生暧昧的SQL查询

@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参考,映射在父级字段中。

有一点我想获得所有的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。

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

提前致谢!

回答

2

尝试使用您定义的别名:

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

嘿malvarez,感谢您的输入。不幸的是,它给出了同样的错误。我也检查了由hibernate生成的查询,并且在两种情况下都完全相同。 – micdcar

+0

对不起,它没有工作。你能用Hibernate生成的查询更新你的问题吗? – malvarez

+0

当然,将这样做;) – micdcar