i have a many to many unidirectional relationship that uses a join table to link orders to books in a simple book store test application. the mapping looks like this:
this creates a join table called orders_books. but now i want to have a way to specify quantity. in this scheme a book can be ordered only once. i guess i could change it to be a list instead of a set but that seems redundant. what i want is to add another column in the orders_books table to specify the quantity. how can i accomplish this with the java persistence api?
posted 8 years ago
You will need to create a Java class to model your BookOrder and add the quantity to it. You will then have a @OneToMany from Order to BookOrder and a @ManyToOne from BookOrder to Order and to Book.
You can either use a composite id for the BookOrder using both the foreign key fields, or add a generated id. I would recommend adding a generated id as it is simpler. If you decide to go with the composite id you will need to add duplicate basic @Id attributes for the foreign keys as JPA does not allow @ManyToOne to be used as an @Id.