Defining a N - M relation of an entity with itself

View: New views
2 Messages — Rating Filter:   Alert me  

Defining a N - M relation of an entity with itself

by maxmil :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

I have an entity A that has a n to m relation with itself. That is to say...

The entity is represented by a table A that has an ID field and various other fields.

The relation is represented by a table B that has two fields ID1 and ID2 where both these fields refer to ID's in table A.

I have one JPA annotated class A which corresponds to the entity. I would like to have a property of this class, relatedAs, that is a list of entities of type A such that in the table B there exists a register with ID1=id of my parent entity and ID2 = A.ID.

Can this be done with JPA o do i need to introduce a relational entity in my java model?

Re: Defining a N - M relation of an entity with itself

by maxmil :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Silly me. Its just the same as any other manyToMany entity.

This is what works for me:

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "B", joinColumns = @JoinColumn(name = "ID1", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "ID2", referencedColumnName = "ID"))
private List relatedAs;
LightInTheBox - Buy quality products at wholesale price!