Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA mapping for Parent-Child with same class

I have following table:

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

I would like to have Folder class to have parent-child relationship.

like image 256
gpa Avatar asked Dec 21 '11 03:12

gpa


1 Answers

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<Folder> subFolders = new ArrayList<Folder>();

}

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.

like image 198
Óscar López Avatar answered Oct 19 '22 23:10

Óscar López