仅针对超类的Hibernate查询

时间:2014-06-10 15:13:01

标签: sql hibernate hql

我扩展了新实体Auditor的域模型,它扩展自实体User。用户是旧实体(数据库表),已经存在。现在,如果对超级用户(仅)执行一些查询,Hibernate也会在审计员表上附加左外连接子句。有没有人知道如何解决它?

用户类

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

审核员班级

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

    private Country countery;
    // ...
}

用户列表的HQL查询示例

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

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

Hibernate generats例如:

 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

1 个答案:

答案 0 :(得分:1)

这是JOINED继承类型的缺点,您无法禁用此功能。 有两种解决方法:
1)使用TABLE_PER_CLASS继承类型

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

2)使用@MappedSuperclass代替@Inheritance

@MappedSuperclass
public class User extends AbstractEntity implements UserDetails {