简体   繁体   中英

Clear ManyToMany Relationship with JPA / JPQL

I have users and roles. And each user can have many roles.

I want to have a bulk operation like remove all User-Roles but keep Users and Roles. So how can i truncate the manyToMany Table only?

The long way would be findAllUsers -> for each user.roles = new Hashset() -> saveAll(users)

@Entity
@Table
public class Role {

    @Id
    @Column(name = "id", unique = true, nullable = false)
    private Long id;

    @ManyToMany(mappedBy = "roles")
    private Set<User> users = new HashSet<>();
}
@Entity
@Table
public class User {

    @Id
    @Column(name = "id", unique = true, nullable = false)
    private Long id;

    @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST})
    @JoinTable(
            name = "UserRole",
            joinColumns = {@JoinColumn(name = "id")},
            inverseJoinColumns = {@JoinColumn(name = "id")})
    private Set<Role> roles = new HashSet<>();
}
@Repository
public interface UsersRepository extends JpaRepository<User, Long> {

    @Modifying
    @Query("UPDATE User u SET u.roles = null")
    void clearAllRoleRelations();
}

I have tried this, but get an exception Not supported for DML operations [UPDATE users.entity.User u SET u.roles = null]

Ditch the @ManyToMany and create an enitity for the join table. This way you'll have full control over the deletion.

I got it working, but with a native query which then requires an entityManager.clear if i want to use this within the same transaction.

    @Modifying
    @Query(nativeQuery = true, value = "DELETE FROM user_role")
    void clearAllRoleRelations();

  @Autowired
  private EntityManager entityManager;
    

  @Test
    public void clearAllRoleRelations() {

        //given
        Role roleIn = new Role();
        roleIn.setId(27L);

        User userIn = new User();
        userIn.Id(12L);

        //do
        roleIn = rolesRepository.save(roleIn);
        userIn = usersRepository.save(userIn);
        userIn.getRoles().add(roleIn);
        usersRepository.save(userIn);

        //verify
        usersRepository.clearAllRoleRelations();

        //important within the same transaction (native query)
        entityManager.clear();

        Optional<User> userOut = usersRepository.findById(userIn.getId());
        assertThat(userOut.isPresent()).isTrue();
        assertThat(userOut.get()).isEqualTo(userIn);
        assertThat(userOut.get().getRoles()).isEmpty();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM