Spring Data JPA多对多,带有额外的列用户和角色

时间:2018-08-31 10:41:03

标签: hibernate spring-mvc spring-boot jpa spring-data-jpa

我想在Setcookie will set persistent cookie with following syntax - setcookie(name,value,expire,path,domain,secure,httponly); // here name is only the mandatory all remainings are optional // now you did not specify the value of expires parameter and // by default it's value is 0 means the cookie will expire at the end of the session (when the browser closes) // following code set cookie for 30 days (60*60*24 = 86400 seconds in a day) and path is current url setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); User实体之间通过Spring Boot JPA使用多对多关系。

我能够使用BUT下面的代码来实现此要求,我需要在数据透视表(Role)中再多一列

users_to_role

这是我的新代码

User.java

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

Role.java

@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
}

UserRole.java

@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
}

有人可以帮助我指出我做错了什么吗?

这是错误堆栈:

@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
}

1 个答案:

答案 0 :(得分:0)

这是因为在${BASH_SOURCE[0]:-$0}的用户实体中,您将@OneToMany指定为mappedBy,而在users实体中,UserRole实体由对象User(不是用户)。 角色实体也是如此。

只需将mappingBy属性中的值与您在user中提到的对象名称同步即可。

第二,在UserRoleUser实体中,您都应该拥有Role(而不是用户或角色列表),因为您将在 users_to_role 中拥有外键桌子。

以下更改将起作用

User.java

List<UserRole>

Role.java

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

UserRole.java

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