hibernate删除多对多延迟集合

t40tm48m  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(251)

我的实体类是:

@Entity
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(unique = true, nullable = false)
    private Long id;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "dt_creation", nullable = false)
    private Date dtCreation;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "dt_maj", nullable = false)
    private Date dtMaj;

    // bi-directional many-to-one 
    @OneToMany(mappedBy = "quality", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<RQulityUser> RQualityUser;

@Entity
public class RQualityUser implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "dt_creation", nullable = false)
    private Date dtCreation;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "dt_maj", nullable = false)
    private Date dtMaj;

    // bi-directional many-to-one association to Questionnaire
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "fk_user", updatable = false, nullable = false)
    private User user;

    // bi-directional many-to-one association to QualitePersonne
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cd_quality_user", updatable = false, nullable = false)
    private Quality quality;

当我得到一个用户并试图清除rqualityuser列表时,我不工作:

User user = em.getByid(11);
 user.getRQualityUserList().clear();

hibernate不删除关系表中的记录?

b5lpy0ml

b5lpy0ml1#

“延迟加载”意味着只有当您第一次实际访问实体时才会加载实体。
当你这么做的时候

user.getRQualityUserList() // Still contains nothing.

所以您正在清除空列表,然后当您使用它时,将从db调用数据。

lbsnaicq

lbsnaicq2#

如果你这么做

User user = em.getByid(11);
user.getRQualityUserList().clear();

对于打开的持久上下文和事务内部,hibernate应该删除记录。
如果你没有交易,你应该使用它。
如果你这样做了 clear() 对于一个封闭的持久上下文,您应该更新 user 删除记录。

相关问题