0

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.

Community
  • 1
  • 1
Hayi
  • 6,972
  • 26
  • 80
  • 139

1 Answers1

1

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.

Neil McGuigan
  • 46,580
  • 12
  • 123
  • 152
  • thanks it was very clear. but for many-to-many relashioship without a extra column the best is to make like this [link](http://www.mkyong.com/hibernate/hibernate-many-to-many-relationship-example-annotation/) and create no auto-generated id field (pseudo-key) ? – Hayi Jun 26 '14 at 15:22
  • Hibernate recommends using meaningless surrogate keys most of the time, so I would go with that as a default choice. – Neil McGuigan Jun 26 '14 at 15:28