persistence@glassfish.java.net

Re: many-to-many self-reference

From: Markus Fuchs <Markus.Fuchs_at_Sun.COM>
Date: Thu, 06 Sep 2007 15:09:08 -0700

Hi Greg,

please try this:

@Entity
public class Category
{
 @Id
 @Column(name="CATEGORY_ID")
 private Long id;

 protected String name;

 @ManyToMany
 @JoinTable(
        name="PARENT_CHILD_CATEGORY",
        joinColumns=_at_JoinColumn(name="PARENT_ID",
referencedColumnName="CATEGORY_ID")
        inverseJoinColumns=_at_JoinColumn(name="CHILD_ID",
referencedColumnName="CATEGORY_ID")
 )
 protected List<Category> parentCategories = new ArrayList<Category>();

 @ManyToMany(mappedBy="parentCategories")
 protected List<Category> childCategories = new ArrayList<Category>();

 ...
}

Thanks,

-- markus.

Greg Ederer wrote:
> Hi,
>
> I have a Category class. According to my model, a Category can have
> many parent Categorys and many child Categorys. I'm having trouble
> getting the JPA annotations right for this relationship. I'm sure that
> this must be trivially easy.
>
> The source might something look like:
>
> @Entity
> public class Category
> {
> @Id
> private Long id;
>
> protected String name;
>
> @???
> protected List<Category> parentCategories = new ArrayList<Category>();
>
> @???
> protected List<Category> childCategories = new ArrayList<Category>();
>
> ...
> }
>
> What is the correct way to do this?
>
> Thanks!
>
> Greg
>