在相应的映射表

时间:2017-02-23 13:24:01

标签: java mysql spring hibernate jpa

在我的Spring-Boot应用程序中,我想在我的数据库中的相应映射表中保存用户角色多对多关系,但是hibernate给了我一条错误消息。

我的 User.java 类:

@Entity
@Table(name = "users")
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  Long id;
  String firstname;
  String lastname;
  String username;
  String password;

  @ManyToMany(mappedBy = "users")
  private Set<Role> roles;
}

我的 Role.java 类:

@Entity
@Table(name = "roles")
public class Role {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  Long id;
  String name;
  String description;

  @ManyToMany(cascade = CascadeType.ALL)
  @JoinTable(
          name = "role_users", 
          joinColumns = 
              @JoinColumn(name = "users_id", referencedColumnName = "id"), 
          inverseJoinColumns = 
              @JoinColumn(name = "roles_id", referencedColumnName = "id")
  )
  private Set<User> users;
}

我的运行 -method:

@Override
@Transactional
public void run(String... strings) throws Exception {
    //add new Roles
    Role roleA = new Role("Rolle A");
    Role roleB = new Role("Rolle B");
    Role roleC = new Role("Rolle C");

    //add new Users
    User userA = new User("FirstnameA", "LastnameA", "UsernameA", "PasswordA");
    User userB = new User("FirstnameB", "LastnameB", "UsernameB", "PasswordB");

    //add new Lists of Roles
    Set<Role> rolesA = new HashSet<Role>();
    rolesA.add(roleA);
    rolesA.add(roleB);
    Set<Role> rolesB = new HashSet<Role>();
    rolesB.add(roleA);
    rolesB.add(roleC);

    //add a list of roles in one user, two times
    userA.setRoles(rolesA);
    userB.setRoles(rolesB);

    //save both users in db
    userRepository.save(userA); //rolle AB
    userRepository.save(userB); //rolle AC

    //give each role the corresponding user
    Set<User> usersA = new HashSet<User>();
    usersA.add(userA);
    usersA.add(userB);
    roleA.setUsers(usersA);
    roleRepository.save(roleA);
    Set<User> usersB = new HashSet<User>();
    usersB.add(userA);
    roleB.setUsers(usersB);
    roleRepository.save(roleB);
    Set<User> usersC = new HashSet<User>();
    usersC.add(userB);
    roleC.setUsers(usersC);
    roleRepository.save(roleC);

}

Hibernate给出了一条错误消息:

  

无法添加或更新子行:外键约束失败(projekt_grarole_users,CONSTRAINT fk_roleusers_user FOREIGN KEY(users_id)参考usersid)ON UPETE CASCADE ON UPDATE CASCADE)

我有来自this site的构造,它可以使用它,但在我的代码中它不起作用。

2 个答案:

答案 0 :(得分:1)

我总是通过将2个@ManyToMany关系重写为@OneToMany到一个新实体来传递这个问题,该实体在中间提供了表格。

一个很好的理由是,当我拥有@ManyToMany关系时,我永远无法轻易得到任何我想要的东西,因为我得到的是产品。将此表作为实体放在中间完全消除了这个问题。

所以,结束:

  • 您已经拥有用户角色类,这些几乎没问题
  • 创建新实体: UserRole ,包含属性:用户用户和角色角色
  • 用户角色中的两个@ManyToMany更改为@ OneToMany到您的新@Entity UserRole
  • UserRole :2 @ManyToOne关系中的关系添加到用户角色

你现在已经解决了问题,并且额外:查询UserRole关系的可能性。

答案 1 :(得分:1)

我解决了! 感谢朋友,我解决了我的问题。如果它对某人感兴趣:我首先尝试将用户保存在存储库中,然后是角色。因为在我想保存用户的那一刻,该角色不存在,Hibernate给了我错误信息。