JpaRepository不会插入多对多数据

时间:2015-09-13 14:59:24

标签: hibernate jpa many-to-many

我有使用JPA Tools生成的用户实体和角色实体。用户和角色具有多对多的关系。我使用以下代码来插入admin,但是没有数据插入到user_role表中。另外我注意到角色类有@JoinTable但是用户类没有它。有差异吗?

private void addAdmin() {
    User admin = new User();
    admin.setDisplayName("admin");

    Role role1 = new Role();
    role1.setRole("ROLE_SUPER_ADMIN");
    Role role2 = new Role();
    role2.setRole("ROLE_END_USER");
    List<Role> roles = new ArrayList<Role>();
    roles.add(role1);
    roles.add(role2);
    admin.setRoles(roles);
    userRepository.save(admin);
}

以下是我的用户类:

@Entity
@NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
  private static final long serialVersionUID = 1L;

  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private int id;

  @Column(name="display_name")
  private String displayName;

  //bi-directional many-to-many association to Role
  @ManyToMany(mappedBy="users")
  private List<Role> roles;
}

以下是我的角色类:

@Entity
@NamedQuery(name="Role.findAll", query="SELECT r FROM Role r")
public class Role implements Serializable {
  private static final long serialVersionUID = 1L;

  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private int id;

  private String role;

  //bi-directional many-to-many association to User
  @ManyToMany
  @JoinTable(
    name="user_role"
    , joinColumns={
        @JoinColumn(name="role_id")
        }
    , inverseJoinColumns={
        @JoinColumn(name="user_id")
        }
    )
  private List<User> users;
}

1 个答案:

答案 0 :(得分:0)

@Entity
public class User {
    @ManyToMany
    private List<Role> roles;
}

@Entity
public class Role {
    @ManyToMany
    private List<User> users;
}

public class Auth {
    User newUser = new User("username","password");
    userDao.save(newUser);

    Role newRole_1 = new Role("ADMIN");
    Role newRole_2 = new Role("USER");
    roleDao.save(newRole_1);
    roleDao.save(newRole_2);

    List<Role> roles = roleDao.findAll();
    User user = userDao.findOne(user_id);  // e.g. Long user_id = 1L;
    for (Role role : roles) {
        user.getRoles().add(role);
    }
    userDao.save(user);

}

如果您创建了新对象:

    User user = new User();
    Role role = new Role();
    List<Role> roles = new ArrayList<>(); 

这些对象是瞬态的,而Hibernate并不适用它们。 Hibernate适用于持久对象。因此,您必须使用方法save();找一个();找到所有();和其他。