Issue
I am writing an online store using Spring Boot
(MVC
) and hiberbate
. I have an order class where I need a Сart
link. But the problem is that in the database I do not have a specific Сart
table, but there is a cart _products
table, where the peimary key
consists of two columns (as shown in the picture below!). I really need a connection in the Order
class, so I decided to make a Composite Primary Key
at the hibernate level (and I seem to have done it), but I can't figure out what to do next! I am stuck. Please tell me where to go? How can I solve my problem?
OrderClass:
@Entity
@Table(name = "pg_order")
public class Order {
// Fields
//
private @Id
@GeneratedValue
Long id;
private String address;
@Column(name = "phone_number")
private String phoneNumber;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "date_order")
private Date dateOrder;
@Enumerated(EnumType.STRING)
@Column(name = "order_status")
private OrderStatus orderStatus;
@Column(name = "total_cost")
private BigDecimal totalCost;
// Relationships
//
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
// @OneToMany
// @JoinColumn(name = "cart_products_pkey")
// private Cart cart;
}
Cart:
@Entity
@Table(name = "cart_products")
public class Cart {
@Embeddable
@NoArgsConstructor
@AllArgsConstructor
static class CartId implements Serializable {
private Long orderId;
private Long drinkId;
}
// Fields
//
@EmbeddedId
private CartId cartId;
@ManyToOne(optional = false)
@JoinColumn(name = "order_id")
private Order order;
@ManyToOne(optional = false)
@JoinColumn(name = "drink_id")
private Drink drink;
private int count;
}
Solution
If you need access to the 'DRINKS' for that order. You need to change the relation to Cart from the Order class.
You have commented a relationship where ORDER just have access to one CART, since you need to access N CARTS (One to Many) you need to add a SET. Something like this:
@OneToMany
@JoinColumn(name = "cart_products_pkey")
private Set<Cart> cartProducts;
Now the ORDER has a SET of CART.
You can easily access to the CARTS of that ORDER with order.getCartProducts()
And since CART has a key to DRINK, you can easily access it.
Hope this can help you.
Answered By - luisfa19