aspose file tools
The moose likes Object Relational Mapping and the fly likes ManyToMany with extra attribute in JPA Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Reply Bookmark "ManyToMany with extra attribute in JPA" Watch "ManyToMany with extra attribute in JPA" New topic
Author

ManyToMany with extra attribute in JPA

Staffan Sandberg
Greenhorn

Joined: May 02, 2008
Posts: 3
I'm making a manyToMany relation between two objects, in JPA, and I want to add an extra property on the relation. I've been following the example found at:
ManyToMay Example

This works fine, but:
1. The relation table in DB will get two id columns for each object, one as primary key and one for the foreign key (=four id columns in total). I only want a total of two id columns + my extra attribute in the relation table/object
2. I have to populate the id-columns manually from my code. I want JPA to handle this
3. I always have to persist the objects to connect before I connect them, in order to get their primary keys.

Is there a better best practice for solving this problem? More like the built in @ManyToMany solution, but with possibility for an extra attribute.
James Sutherland
Ranch Hand

Joined: Oct 01, 2007
Posts: 550
You are getting duplicate primary/foreign key values because both the @ManyToOne and @Id map the same field, you need to mark one of these as read-only. This is done in JPA either through setting insertable=false, updateable=false, or by using a @PrimaryKeyJoinColumn.

See:
http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Primary_Keys_through_OneToOne_Relationships

There is nothing in JPA 1.0 to make this easier, although JPA 2.0 will hopefully make things easier when it is released.

Most JPA providers let you use ManyToOne and OneToOne mappings as part of your object's id. Both Hibernate and TopLink/EclipseLink have ways to do this. This avoids the duplicate mappings and does not require to persist your objects before relating them.

Most JPA provider have additional mappings types as well, although I'm not sure any would be better to handle your model.


TopLink : EclipseLink : Book:Java Persistence : Blog:Java Persistence Performance
Nicolas Allo
Greenhorn

Joined: Feb 26, 2009
Posts: 4
Does Somebody find a solution for this particularity?
thanks
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: ManyToMany with extra attribute in JPA
 
Similar Threads
Putting it together: Struts, Tags, OGNL
Composite Primary key mapping problem with one-to-one Relation
Hibernate: one class many tables
How could I map this situation: ManyToMany with own PK
Mapping two Hibernate Object based on their foriegn keys