Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ManyToMany with extra attribute in JPA

 
Staffan Sandberg
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 553
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Nicolas Allo
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does Somebody find a solution for this particularity?
thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic