Peter Jurkovic
Peter Jurkovic

Reputation: 2896

Hibernate query for super class only

I extended domain model of new entity Auditor, which extends from entity User. User is old entity (database table), which has existed already. Now, if is executed some query for super class User (only), Hibernate appends left outer join clause on auditor's table too. Does anyone have an idea how to solve it?

User class

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "users")
@DiscriminatorColumn(length = 10, name = "discriminator", 
    discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue("user")
@SequenceGenerator(name = "users_id_seq", 
    sequenceName = "users_id_seq", 
    initialValue = 1, allocationSize =1)
public class User extends AbstractEntity implements UserDetails{

    private static final long serialVersionUID = 198524L;

    private Long id;
    // ...
}

Auditor class

@Entity
@Table(name = "auditor")
@DiscriminatorValue("auditor")
public class Auditor extends User {

    private Country countery;
    // ...
}

Example of HQL query for User list

Query query = sessionFactory.getCurrentSession()
    .createQuery("select type(u) from User u");

return Collections.checkedList(query.list(), User.class);

Hibernate generats e.g.:

 select
        case 
            when user0_1_.id is not null then 1 
            when user0_.id is not null then 0 
        end as col_0_0_ 
    from
        users user0_ 
    left outer join
            auditor user0_1_ 
            on user0_.id=user0_1_.id 
  group by
        user0_.id 
order by

Upvotes: 3

Views: 1736

Answers (1)

Ilya
Ilya

Reputation: 29693

This is disadvantage of the JOINED inheritance type and you cann't disable this feature. There are two workarounds:
1) Use TABLE_PER_CLASS inheritance type

@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class User extends AbstractEntity implements UserDetails {  

2) use @MappedSuperclass instead of @Inheritance

@MappedSuperclass
public class User extends AbstractEntity implements UserDetails {

Upvotes: 1

Related Questions