Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attributes on Many-to-Many relationships (Hibernate)

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

like image 902
niklassaers Avatar asked Sep 25 '09 10:09

niklassaers


People also ask

What should be done for many-to-many joins in hibernate?

In order to map a many-to-many association, we use the @ManyToMany, @JoinTable and @JoinColumn annotations. Let's have a closer look at them. The @ManyToMany annotation is used in both classes to create the many-to-many relationship between the entities.

What is one to many and many-to-one relationship in hibernate?

One To Many Mapping in Hibernate. In simple terms, one to many mapping means that one row in a table can be mapped to multiple rows in another table. For example, think of a Cart system where we have another table for Items. A cart can have multiple items, so here we have one to many mapping.

What is MappedBy attribute in hibernate?

MappedBy signals hibernate that the key for the relationship is on the other side. This means that although you link 2 tables together, only 1 of those tables has a foreign key constraint to the other one. MappedBy allows you to still link from the table not containing the constraint to the other table.


2 Answers

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.

like image 53
KLE Avatar answered Oct 21 '22 22:10

KLE


See

@ManyToMany Hibernate Question (can add extra field?)

And

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

regards,

like image 35
Arthur Ronald Avatar answered Oct 21 '22 20:10

Arthur Ronald