Spring Boot多对多重复记录

时间:2019-03-04 10:05:11

标签: java spring hibernate jpa spring-data-jpa

我正在尝试使用Spring Boot创建用户管理API。 (代码优先)

添加新用户时遇到问题。
例如,如果我在角色表中添加 root_1-admin和root_2-admin ,则我有两条记录

角色表:

[id]  [name]
 1    admin
 2    admin

enter image description here

型号: 用户

@Data
@Entity
public class AppUser {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String username;
    private String password;
    private String firstName;
    private String lastName;
    //@ManyToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
    @ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles;

    public AppUser() {
    }

    public AppUser(String username, String password, String firstName, String lastName, Set<Role> roles) {
        this.username = username;
        this.password = password;
        this.firstName = firstName;
        this.lastName = lastName;
        this.roles = roles;
    }

}

角色

@Data
@Entity
public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
}

服务 UserServiceImpl

    @Override
    public void addUser(AppUser user) {

        user.setPassword(encoder.encode(user.getPassword()));

        userRepository.save(user); // JpaRepository
    } 

0 个答案:

没有答案