【问题标题】:Unable to remove childs in OneToMany Mapping and add new childs [Hibernate]无法在 OneToMany 映射中删除孩子并添加新孩子 [休眠]
【发布时间】:2020-11-14 00:09:24
【问题描述】:

我知道这个问题已被问过很多次,但没有一个解决方案适合我。

所以我有一个父类:

class User{

@Id
@NotNull
@Column(name = "`UserId`", nullable = false)
private Long userId;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinColumn(name = "`UserId`")
private Set<Phone> phoneList;
}

还有一个子类:

class Phone {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "`UserId`")
private User user;
}

现在,当我收到包含新手机列表的用户类更新时,我想删除所有旧手机并添加新手机。请注意,这所有操作都发生在同一个 @Transactional 中。

我尝试过的解决方案:

user.getPhoneList().clear()
user.getPhoneList().addAll(新手机列表)

当我尝试上述逻辑时,Hibernate 正在尝试将旧手机的 userId 设置为 null。在这个位置,我得到 DataIntegrityViolation,因为 Phone 表中的 userId 是非空列。

请提供任何可以在此处使用的适当解决方案。

【问题讨论】:

    标签: java hibernate mapping orphan-removal


    【解决方案1】:

    Hhhmmm...我有完全相同的逻辑,它对我来说很好。这是我的课

    @Data
    @Entity
    public class ProductReference {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    
    
    @OneToMany(mappedBy = "productReference", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE, orphanRemoval = true)
    private Set<Attribute> attributes = new HashSet<>();
    
    }
    

    我看到的唯一区别是CascadeType.REMOVE

    @Data
    @Entity
    public class Attribute {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    
    @ManyToOne
    private ProductReference productReference;
    }
    

    我的删除:

    productReference.getAttributes().clear();
    

    你有哪个 Hibernate 版本?我是org.hibernate.Version - HHH000412: Hibernate Core {5.4.10.Final}

    【讨论】:

    • 休眠版本:5.4.12
    • @JoinColumn 有什么不同吗?
    • 嗯,我不确定......我在这里找到什么,我会说不(baeldung.com/jpa-join-column)。但我想说,试试看吧。
    • 你还有getter和setter吗?
    猜你喜欢
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多