title: Hibernate generates ambiguous SQL query
body: <p>Consider the following <strong>ParentClass</strong> entity:</p>
  
  <pre><code>@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;
      }
  }
  </code></pre>
  
  <p>And the following <strong>ChildClass</strong> entity:</p>
  
  <pre><code>@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);
      }
  }
  </code></pre>
  
  <p>As you can see, this ChildClass extends from ParentClass. Moreover, it contains a reference for ParentClass mapped in <strong>parent</strong> field.</p>
  
  <p>There is a point where I want to get all instances of ParentClass, but not the instances that are ChildClass.</p>
  
  <p>I searched around and found that could be achieved with this criteria:</p>
  
  <pre><code>Criteria criteria = sessionFactory.getCurrentSession()
                  .createCriteria(ParentClass.class, "parentClass")
                  .add(Restrictions.eq("class", ParentClass.class));
  </code></pre>
  
  <p>However, when I try to list it, I get the following error:</p>
  
  <blockquote>
    <p>ERROR SqlExceptionHelper:147 - ERROR: column reference "clazz_" is
    ambiguous</p>
  </blockquote>
  
  <p>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.</p>
  
  <p>Here is the query generated by hibernate when I have all the restrictions:</p>
  
  <blockquote>
    <p>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_=?</p>
  </blockquote>
  
  <p>Working example available here: <a href="https://github.com/mmalmeida/hibernateTest" rel="nofollow noreferrer">https://github.com/mmalmeida/hibernateTest</a> , just run the test RetrieveParentTest.java.</p>
  
  <p>Do you know how I can work around this problem?</p>
  
  <p>Thanks in advance!</p>