views:

468

answers:

2

Hi guys,

I have entity classes A and C. They are mapping the tables tblA and tblC and have a many-to-many relationship between them, with tblB to map between them. tblB contains A_ID, C_ID and SetDate, the last one being the date it was set, thus an attribute to the relationship. My question is, how do I best map in this attribute? At the moment they're unmapped, like this:

A:

@ManyToMany(targetEntity=C.class, cascade={ CascadeType.PERSIST, CascadeType.MERGE } )
@JoinTable(name="tblB", joinColumns=@JoinColumn(name="A_ID"), inverseJoinColumns=@JoinColumn(name="C_ID") )
private Collection<C> Cs;

C:

@ManyToMany( cascade = {CascadeType.PERSIST, CascadeType.MERGE}, mappedBy = "Cs", targetEntity = A.class )
private Collection<A> As;

How should I get tblB.SetDate out of this?

Cheers

Nik

+1  A: 

See

@ManyToMany Hibernate Question (can add extra field?)

And

how to make a composite primary key (java persistence annotation)

regards,

Arthur Ronald F D Garcia
Of course I could add a new entity, with the increased amount of code, but I'd like to keep the code level down. I'd prefer to just add an attribute to the relationship if there's any way of doing that
niklassaers
@niklassaers I think there is no way but if you get it, share it with us. regards,
Arthur Ronald F D Garcia
Thanks Arthur, I will. :-)
niklassaers
+2  A: 

From what I know, it is not possible to map it this way, you have to switch to One-To-Many and a Many-To-One relationships, with your B in the middle. Your date will be an attribute of B.


For this lack of evolutivity, the Hibernate documentation recommends to avoid the Many-To-Many in general, and use the two relationships from the beginning.

KLE
Hi, thanks for your input. Avoiding many-to-many while keeping the amount of entity classes down may not always be possible when mapping legacy databases like I am doing now.
niklassaers
I must cope with the legacy database stuff too ! I also share your desire for keeping down the number of classes. In that case though, if you need an extra field, I'm not sure you have other options...
KLE