JPA mapping for Parent-Child with same class

前端 未结 1 774
借酒劲吻你
借酒劲吻你 2021-02-04 03:42

I have following table:

FOLDER[
    id int,
    name varchar2(10),
    parent_folder_id int
]

I would like to have Folder class to have parent-

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-04 04:20

    I believe the correct mapping would be:

    @Entity
    public class Folder {
    
        @Id
        @Column(name="PK_FOLDER")
        private int id;
    
        @Column(name="NAME")
        private String name;
    
        @ManyToOne
        @JoinColumn(name="FK_PARENT_FOLDER")
        public Folder parentFolder;
    
        @OneToMany(mappedBy="parentFolder")
        public List subFolders = new ArrayList();
    
    }
    

    The @OneToOne would work only if each parent had at most one child, the above code works for the more general case, when a parent can have many children. Also, I'm omitting get/set methods for simplicity's sake.

    0 讨论(0)
提交回复
热议问题