代码之家  ›  专栏  ›  技术社区  ›  VK321

Spring数据JPA多对多,具有额外的列用户和角色

  •  0
  • VK321  · 技术社区  · 8 年前

    User Role 实体。

    我能够实现这一点,使用下面的代码,但在我的要求,我需要 一个额外的列 在透视表中( users_to_role ).

    @ManyToMany
    @JoinTable(
            name = "users_to_roles",
            joinColumns = @JoinColumn(
                    name = "user_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(
                    name = "role_id", referencedColumnName = "id"))
    private List<Role> roles;
    

    @Entity
    @Table(name = "users")
    public class User {
    
       @Id
       @GeneratedValue(strategy = GenerationType.IDENTITY)
       private Long id;
    
       private String username;
    
       @OneToMany(mappedBy="users", cascade = CascadeType.ALL)
       private List<Role> roles;
    
       //getters and setters here
    }
    

    @Entity
    @Table(name = "roles")
    public class Role {
    
       @Id
       @GeneratedValue(strategy = GenerationType.IDENTITY)
       private Long id;
    
       private String name;
    
       @OneToMany(mappedBy="roles", cascade = CascadeType.ALL)
       private List<User> users;
    
       //getters and setters here
    }
    

    用户角色.java

    @Entity
    @Table(name = "users_to_role")
    public class UserRole {
    
       @Id
       @ManyToOne
       @JoinColumn(name = "user_id")
       private User user;
    
       @Id
       @ManyToOne
       @JoinColumn(name = "role_id")
       private Role role;
    
       private Date createdAt;
    
      //getters and setters here
    }
    

    下面是错误堆栈:

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Illegal use of mappedBy on both sides of the relationship: com.example.entities.Role.users
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   VK321    8 年前

    这是因为在您的用户实体中 @OneToMany mappedBy 作为 users 在你的房间里 UserRole User 实体由对象表示 user 角色实体的情况也类似。

    用户角色 .

    其次是两者 Role 你应该拥有的实体 List<UserRole> (不是用户或角色的列表),因为您将在 用户到角色 桌子。

    用户.java

    @OneToMany(mappedBy="user", cascade = CascadeType.ALL)
    private List<UserRole> roles;
    

    @OneToMany(mappedBy="role", cascade = CascadeType.ALL)
    private List<UserRole> users;
    

    用户角色.java

    public class UserRole implements Serializable {}