Thursday, November 01, 2007

EJB3.0 Persistence Relationships

The EJB 3.0 persistence relationships via annotations always elude me, so I figured I should take note of them here now that I got it right (finally).
Suppose you want to express the idea that an activity is done on one task at a time by one user. Three objects are involved: Activity, User, Task. To build a database relation between these:
Activity(n)<->(1)User = @ManyToOne in Activity, @OneToMany in User. :: Activity can be associated with only one user while User can be associated with many activities.
Activity(n)<->(1)Task = @ManyToOne in Activity, @OneToMany in Task. :: Activity can be associated with only one task while Task can be associated with many activities.
User(1)<->(n)Task = @OneToMany in User, @ManyToOne in Task. :: A user can have many tasks, but a task can be owned by at most one user.
@ManyToMany is trivial and the commonest used.

For a person without the mental picture of database relationships, these simple rules will help.

No comments: