Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate query for super class only

Tags:

sql

hibernate

hql

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
like image 772
Peter Jurkovic Avatar asked Feb 13 '26 15:02

Peter Jurkovic


1 Answers

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 {
like image 96
Ilya Avatar answered Feb 15 '26 05:02

Ilya