欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot + JPA @ManyToMany 操作要点

程序员文章站 2022-05-02 09:36:43
...

SpringBoot + JPA @ManyToMany 要点

这里主要时记录下此种方法的注意事项。

对应的Entity的建立。此处注意不可使用lombok @Data 注解。使用@Setter 、@Getter注解。主要原因时要自己覆写hash() equals(),toString() 方法。这样添加和删除的时候不会出现异常。否则出现循环的引用,不能删除或stackOver;

User

@Setter
@Getter
@Entity
public class User {


    @Id
    @GenericGenerator(name="jpauuid",strategy = "org.hibernate.id.UUIDGenerator")
    @GeneratedValue(generator = "jpauuid")
    @Column(length = 32,nullable = false)
    private String  id;

    @Column(length = 30)
    private String username;

    @ManyToMany(cascade = CascadeType.REFRESH,mappedBy = "users")
    @JsonBackReference  //防止无限引用
    private Set<Role> roles;


    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return id.equals(user.id) &&
                username.equals(user.username) &&
                roles.equals(user.roles);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, username, roles);
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", username='" + username + '\'' +
                ", roles=" + roles +
                '}';
    }
}


Role


@Setter
@Getter
@Entity
public class Role {

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

    @Column(length = 30)
    private String  name;


    @ManyToMany(cascade = CascadeType.REFRESH)
    @JoinTable(name = "user_role",joinColumns = @JoinColumn(name = "role_id"),inverseJoinColumns = @JoinColumn(name="user_id"))
    private Set<User>  users;


    public void addUser(User user){
        this.users.add(user);
    }


    public void removeUser(User user){
        this.users.remove(user);
    }

}


Junit的测试 注意@transaction的注解一定要加上。

   /**
     * 添加角色
     */
    @Test
    public void addRole(){
        Role role = new Role();
        role.setName("系统管理员");
        roleRepository.save(role);
    }

    /**
     * 添加用户
     */
    @Test
    public void addUser() {
        User user = new User();
        user.setUsername("test1");
        userRepostitory.save(user);
    }

    /**
     *
     * 通过关系维护方添加角色和用户的关系
     */
    @Test
    @Transactional
    public void  addUserRole(){
        User user = userRepostitory.findByUsername("test1");
        Role role = roleRepository.getOne(1);
        role.addUser(user);
        roleRepository.saveAndFlush(role);
    }

    /**
     *
     * 删除对应的关联数据
     */
    @Test
    @Transactional
    public void removeRoleUser(){
        User user = userRepostitory.findByUsername("test1");
        Role role = roleRepository.getOne(1);
        role.removeUser(user);
        roleRepository.saveAndFlush(role);
    }