JPA Persist parent and child with one to many relationship

前端 未结 5 567
我寻月下人不归
我寻月下人不归 2020-12-24 08:13

I want to persist parent entity with 20 child entities, my code is below

Parent Class

@OneToMany(mappedBy = \"parentId\")
private Collection

        
5条回答
  •  渐次进展
    2020-12-24 08:27

    I would let the parent persist it's own children

    package com.greg;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.OneToMany;
    
    @Entity(name = "PARENT")
    public class Parent {
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
    
        @Column(name = "NAME")
        private String name;
    
        @Column(name = "DESCRIPTION")
        private String description;
    
        @OneToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER)
        @JoinColumn(name = "parent", referencedColumnName = "id", nullable = false)
        private List children = new ArrayList();
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getDescription() {
            return description;
        }
    
        public void setDescription(String description) {
            this.description = description;
        }
    
        public List getChildren() {
            return children;
        }
    
        public void setChildren(List children) {
            this.children = children;
        }
    
    }
    

提交回复
热议问题