JPA mapping for Parent-Child with same class

gpa picture gpa · Dec 21, 2011 · Viewed 11.6k times · Source

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.

Answer

Óscar López picture Óscar López · Dec 21, 2011

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.