簡體   English   中英

清除與 JPA / JPQL 的多對多關系

[英]Clear ManyToMany Relationship with JPA / JPQL

我有用戶和角色。 每個用戶可以有很多角色。

我想要進行批量操作,例如刪除所有用戶角色但保留用戶和角色。 那么我怎樣才能只截斷 manyToMany 表呢?

很長的路要走 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();
}

我已經嘗試過了,但是得到了一個異常不支持 DML 操作 [UPDATE users.entity.User u SET u.roles = null]

@ManyToMany並為連接表創建一個實體。 這樣您就可以完全控制刪除。

我讓它工作了,但是使用本機查詢,如果我想在同一個事務中使用它,則需要 entityManager.clear。

    @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();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM