Search code examples
hibernatejpahibernate-criteria

Hibernate inheritance: join query with criteria


I have an entity AA that has a many to many relationships with an entity BB and BB extend another entity CC ( with inheritance strategy JOIN).

    @Entity
    class AA {

   @ManyToMany
   @JoinTable(name = "AA_BB", joinColumns = @JoinColumn(name = "ID_AA", referencedColumnName = "ID_AA"), inverseJoinColumns = @JoinColumn(name = "ID_BB", referencedColumnName = "ID_BB"), uniqueConstraints = @UniqueConstraint(columnNames = {
        "ID_AA", "ID_BB" }))
    private List<BB> bb = new ArrayList<>();
    }

    @Entity
    class BB extends CC {
    }

    @Entity
    @Inheritance(strategy = JOINED)
    abstract class CC {

    @Column
    private long code;

    }

I am trying to create a query with criteria to retrieve all the AA that has a list of BB that contains a code equal to 100.

The following code doesn't work and I am getting an exception of type: nested exception is org.hibernate.ObjectNotFoundException: No row with the given identifier exists

            criteria.createAlias("bb", "b", JoinType.INNER_JOIN);
            criteria.add(Restrictions.eq("b.code", 100));

Solution

  • According to comment - you need create criteria for both master (AA), and detail (BB). Here is something that should work:

    Criteria aaCriteria = getCurrentSession().createCriteria(AA.class,"a");
    Criteria bbCriteria = aaCriteria.createCriteria("bb","b");
    bbCriteria.add(Restrictions.eq("b.code", 100));
    

    Having criteria object for both levels you can add restrictions for both of them.