【问题标题】:JPA delete child without deleting parentJPA删除孩子而不删除父母
【发布时间】:2020-07-08 20:50:16
【问题描述】:

我使用的是 Spring Boot 2.3.0。

我的一侧是多对一关系,另一侧是单对多关系。一位父母对许多孩子,但许多孩子对一位父母。我试图能够在不影响父母的情况下删除孩子。我在父字段的子端有nullable = false,因为我不想最终在 parent_to_child 表中为父级意外空值。我希望这样的事情得到执行并被抓住。

当我从Reader 对象(这是父对象)中的List<TBRList> 中删除其中一个TBRList 项目(这是子对象)后执行readerRepository.save(reader) 时,我不断收到有关父对象的错误尝试删除子项时字段不能为空。如果我在子对象的父字段上将 nullable 设置为 false,我的父级就会消失。

我以为我明白这应该如何工作,但显然不是。

我有:

@Entity //parent
public class Reader implements Serializable {

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

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "reader", orphanRemoval = true)
    Set<TBRList> tbrLists = new HashSet<>();

    //other fields, getters, setters, etc.
}



@Entity(name = "tbr") //child
public class TBRList implements Serializable {
    
    @Id
    @GeneratedValue(strategy = IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @JsonIgnore
    @ManyToOne
    @JoinColumn(name = "reader_id", nullable = false)
    private Reader reader;

    //other fields, getters, setters, etc
}

在下面的 sn-p 中,readerRepository.save(reader) 是发生 org.hibernate.PropertyValueException: not-null property references a null or transient value : com.me.project.entity.TBRList.reader 异常的地方。

if (reader.hasTBRList(tbrListName)) {
    Iterator<TBRList> it = reader.getTbrLists().iterator();
    while (it.hasNext()) {
        TBRList tbrList = it.next();
        if (tbrList.getName().equals(tbrListName)) {
            it.remove();
            readerRepository.save(reader);
            break;
        }
    }
}

我还尝试通过tbrListRepositoryTBRListdelete 中的reader 设置为null,但同样的事情发生了。事实上,我尝试了太多的事情来记住它们(我尝试在数小时的搜索和尝试之后提出问题作为最后的结果)。

我在尝试建立父/子关系时做错了什么,我不希望 Child.parent 为空,并且我希望能够从父级中删除子级而不删除父级中的父级过程?

【问题讨论】:

    标签: java spring-boot jpa spring-data-jpa


    【解决方案1】:

    我创建了相同的类,我得到这个结果来按你的意愿执行:

    @Entity(name = "tbr")
    @Data
    public class TBRList {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
    
        @Column(nullable = false)
        private String name;
    
        @JsonIgnore
        @ManyToOne(fetch = FetchType.EAGER)
        @JoinColumn(name = "reader_id", nullable = false)
        private Reader reader;
    
    }
    
    
    @Entity
    @Data
    public class Reader {
        
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @JsonIgnore
        private Long id;
    
        @OneToMany(cascade = CascadeType.ALL, mappedBy = "reader", orphanRemoval = true)
        Collection<TBRList> tbrLists ;
    
    
    }
    

    【讨论】:

    • 尝试时没有变化。
    猜你喜欢
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多