'JPA Composite Key: Avoid Unnecessary of Table Creation
I am learning JPA.
I need to create 3 tables, product (pk => id), cart (pk => id), cart_details (pk also fk => product_id, cart_id).
The relation is : One cart can contain multiple cart_details, one cart_details can contain multiple product and one product can be put on multiple cart_details. I need only 3 tables, but JPA creates 4 tables for me: product, cart, cart_details, cart_details_product
@Entity
@Table(name = "product")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@NotBlank
@Size(max = 50)
private String name;
@Size(max = 300)
private String description;
@NotNull
private Double price;
private int qty;
@Column(name = "created_date")
private Date createdDate;
@Column(name = "updated_date")
private Date updatedDate;
}
@Entity
@Table(name = "cart")
public class Cart implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "total_price")
private double totalPrice;
@Column(name = "created_date")
private Date createdDate;
@Column(name = "updated_date")
private Date updatedDate;
}
@Entity
@Table(name = "cart_details")
public class CartDetails implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
private CartDetailsId id;
@MapsId("cartId")
@ManyToOne
@JoinColumn(name = "cart_id", referencedColumnName = "id", insertable = false, updatable = false)
private Cart cart;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "product_id", referencedColumnName = "id")
private Set<Product> product;
private int quantity;
private double price;
}
@Embeddable
public class CartDetailsId implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name = "cart_id")
private Long cartId;
@Column(name = "product_id")
private Long productId;
}
How to avoid creation of this table (cart_details_product)? I think i don't need this table.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

