代码之家  ›  专栏  ›  技术社区  ›  bobndrew Daniel Hiller

如何一次删除Hibernate JoinTable中的所有关联?

  •  5
  • bobndrew Daniel Hiller  · 技术社区  · 16 年前

    @Entity
    public class Role {
      ...
      @ManyToMany
      @JoinTable( name = "user_has_role", joinColumns = { @JoinColumn( name = "role_fk" ) }, inverseJoinColumns = { @JoinColumn( name = "user_fk" ) } )
      private Set<User>           userCollection; 
      ...
    }
    

    @Entity
    public class User {
      ...
      //bi-directional many-to-many association to Role
      @ManyToMany( mappedBy = "userCollection" )
      private Set<Role>        roleCollection;
      ...
    }
    

    em.createQuery( "DELETE Role" ).executeUpdate();
    

    this answer

    for ( ... )
    {
        A a = aDao.getObject(aId);
        B b = bDao.getObject(bId);
    
        b.getAs().remove(a);
        a.getBs().remove(b);
        bDao.saveObject(b); 
    }
    

    有没有一种方法可以在不遍历所有数据的情况下一次删除JoinTable中的所有关联? 可能有一个特殊的HQL命令,比如 DELETE Role.user_has_role ?

    1 回复  |  直到 9 年前
        1
  •  3
  •   Pascal Thivent    16 年前

    虽然JPA规范明确指出批量操作不是级联到 相关实体 HHH-1917 . 解决方法:使用本机SQL。