Reputation: 6236
I have a many-to-many relationship :
customer
, product
, customer_product
with extra column quantity
i want to map them with hibernate my question is :
what i will loose if i just map them normally like two one-to-many ?
customer_product
will have just one primary key (id_customer_product
) and not a composite primary key (id_product
+ id_customer
)
customer
Entity:
@Entity
@Table(name = "customer", catalog = "XX")
public class Customer implements java.io.Serializable {
@OneToMany(fetch = FetchType.LAZY, mappedBy = "customer")
private Set customer_product = new HashSet<Customer_Product>(0);
}
product
Entity:
@Entity
@Table(name = "product", catalog = "XX")
public class Customer implements java.io.Serializable {
@OneToMany(fetch = FetchType.LAZY, mappedBy = "product")
private Set customer_product = new HashSet<customer_product>(0);
}
customer_product
Entity:
@Entity
@Table(name = "customer_product", catalog = "XX")
public class Customer_Product implements java.io.Serializable {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "ID_customer_product")
private Integer ID_customer_product;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ID_customer")
private Customer customer;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ID_product")
private Product product;
}
Or i have to make like this answer and make a composite primary key.
Upvotes: 0
Views: 88
Reputation: 48236
First, what is a Customer Product? This looks like a standard Sales Order model.
Don't make it a simple Many-To-Many relationship. Use One-To-Many on both sides. You're on the right track, though I don't see your Quantity field anywhere.
A Customer hasMany CustomerProducts. A Product hasMany CustomerProducts. A CustomerProduct belongsTo a Customer and belongsTo a Product.
If you want to use an auto-generated id field, then that is your primary key. You can add a unique constraint on (customer,product) if you don't want duplicate lines by customer and product.
Upvotes: 1