How to implement many to many relationship with hibernate?
Hello guys!Is this a bad solution/workaround to implement a many to many relationship?
Correct me if I'm wrong but normaly we should avoid many to many relationships.
And to avid it we implement a "connection"-table
Please consider this example.
Order <- OrderRows -> Article
ORDER
*id
name
ORDERROWS
*fk_order_id
*fk_article_id
quantity
ARTICLE
id
name
price
A order now could have many articles and an article could could exist in many orders.
How ever this seems hard to implement in hibernate with a composite key in the ORDERROWS table.
I did it like this:
@Entity
@Table(name = "Orders")
public class Orders {
@Id
@GeneratedValue
private String id;
private String name;
}
@Entity
@Table(name = "ARTICLES")
public class Article {
@Id
@GeneratedValue
private String id;
private String name;
private String price;
}
I alter the table ORDERROWS to have one primary key instead of a composite key
ORDERROWS
*id
fk_order_id
fk_article_id
quantity
And create a unique index over the two fk-keys to make sure there will be no duplicate rows.
@Entity
@Table(name = "ORDERROWS")
public class OrderRows {
@Id
@GeneratedValue
private String id;
@ManyToOne
@JoinColumn(name="fk_orderId")
private Order order;
@ManyToOne
@JoinColumn(name="fk_articleId")
private Article article;
private String quantity;
}
What I can see the drawback to this is that I will get en extra column in the DB that consumes memory.
I do not find any other solutions like mine so I bet there might be a good reason and that I'm wrong somewhere.
If you see any "stupidness" or otehr drawbacks in this workaround please let me know.
Best regards
Fredrik