Friday, March 19, 2010

Many-To-Many self reference in Java Persistence API

    Think of the following scenario: you need a many-to-many relationship between a table and itself... how can you accomplish that with JPA annotations ?
    Suppose we have a table Tasks in the database which is mapped to an Entity named Task. A task entry should have a list of parent tasks (prerequisite tasks if you want) and a list of child tasks (tasks which upon the current task's completion would enable them to start). The Task entity class would look a little something like this:

@Entity
@Table (name = "Tasks" , schema = "ProjectManagement" )
public class Task implements Serializable {

// Mandatory @Id PK field

//constructors (including a no-arg constructor)

//fields

// getters and setters


@ManyToMany
@JoinTable ( name = "parent_child_task" ,
                    joinColumns = @JoinColumn ( name = "child_id" , referencedColumnName = "id" ),
                    inverseJoinColumns = @JoinColumn ( name = "parent_id" , referencedColumnName = "id" ))
private List<Task> prerequisiteTasks = new ArrayList<Task>();

@ManyToMany (mappedBy = "prerequisiteTasks" )
private List<Task> childTasks = new ArrayList<Task>();

//.... more

}

Hope this makes sense

1 comment:

Rudy said...

Thanks a million! I was scouring the internet in search of a good example and this provided me with exactly what I was looking for.