简体   繁体   中英

Hibernate generates ambiguous SQL query

Consider the following ParentClass entity:

@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;
    }
}

And the following ChildClass entity:

@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);
    }
}

As you can see, this ChildClass extends from ParentClass. Moreover, it contains a reference for ParentClass mapped in parent field.

There is a point where I want to get all instances of ParentClass, but not the instances that are ChildClass.

I searched around and found that could be achieved with this criteria:

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

However, when I try to list it, I get the following error:

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

If I remove the last line of the criteria, the query is successfully executed. But the ChildClass instances are also returned, which is not what I want.

Here is the query generated by hibernate when I have all the restrictions:

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_=?

Working example available here: https://github.com/mmalmeida/hibernateTest , just run the test RetrieveParentTest.java.

Do you know how I can work around this problem?

Thanks in advance!

Try using the alias you defined:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM