1

我有 3 个与 Hibernate 一起正常工作的 Java 类(BaseEntity、User、Role)。User 和 Role 都是 BaseEntity 的子类。我有一个用于我的用户的表和一个用于我的角色的表。有一个用于将用户映射到角色的连接表。所有使用的注解都是javax.persistence注解。

@MappedSuperclass
public abstract class BaseEntity {
   private String id;
   private Timestamp entityCreation;
   private Timestamp entityUpdate;
   ...
}

@Entity
@Table(name="roles")
public class Role extends BaseEntity {
   private String description;
   private String name;
   ...
}

@Entity
@Table(name="users")
public class User extends BaseEntity {
   private String username;
   private String password;

   @ManyToMany( cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }, fetch = FetchType.LAZY )
   @JoinTable( name = "users_roles", joinColumns = { @JoinColumn( name = "user_id" ) }, inverseJoinColumns = { @JoinColumn( name = "role_id" ) } )
   private Set<Role> roles;
   ...
}

由于各种原因,我需要扩展我的模型并为角色创建一个超类。这个超类需要有一个自引用。我的想法是在此处将 @Inheritance 注释与连接策略一起使用,但我不断收到来自 Hibernate 的错误。从我读到的 Hibernate 应该明白,它需要进行连接才能从超类中获取属性。

@Entity
@Table("authorities")
@Inheritance(strategy=InheritanceType.JOINED)
public class Authority extends BaseEntity {
   private String name;

   @ManyToMany( cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }, fetch = FetchType.LAZY )
   @JoinTable( name = "authorities_includes", joinColumns = { @JoinColumn( name = "authority_id" ) }, inverseJoinColumns = { @JoinColumn( name = "include_id" ) } )
   private Set<Authority> includes;
   ...
}

@Entity
@Table(name="roles")
public class Role extends Authority {
   private String description;
   ...
}

我得到的错误:

[警告] [18:30:04.004] [] org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL 错误:-5501,SQLState:42501 [错误] [18:30:04.004] [] org.hibernate.engine .jdbc.spi.SqlExceptionHelper - 用户缺少权限或找不到对象:ROLE1_.NAME

休眠 SQL 输出:

[DEBUG] [18:30:04.004] [] org.hibernate.SQL - 
    select
        roles0_.user_id as user_id1_22_1_,
        roles0_.role_id as role_id2_23_1_,
        role1_.id as id1_18_0_,
        role1_.entity_creation as entity_c2_18_0_,
        role1_.entity_update as entity_u3_18_0_,
        role1_.name as name4_18_0_ 
    from
        odm_users_roles roles0_ 
    inner join
        odm_roles role1_ 
            on roles0_.role_id=role1_.id 
    where
        roles0_.user_id=?

我正在使用休眠 4.2.19

如您所见,Hibernate 试图从权限表中选择 name 属性的值,这是正确的,但随后抱怨该表上不存在该列。

我该如何解决这个问题?

4

0 回答 0