Tenho um relacionamento Product
⎯⎯⎯⎯◆ Item
⎯⎯⎯◆ ShoppingCart
e criei um mapeamento @ManyToMany
entre Product
e ShoppingCart
, e, Item
como tabela resultante desse relacionamento, de acordo com a UML na imagem abaixo. Mas apesar da tabela está sendo gerada corretamente, e os dados estarem sendo gravados, não consigo retornar o JSON de ShoppingCart. Como posso fazer esse mapeamento (ManyToMany c/ dados extras) da forma correta?
Seguem a UML do projeto, o print do erro, e o link do projeto no GitHub (veja a brach temp/tony):
- Erro:
Product:
package com.supera.games.domain.model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Transient;
@Entity
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
public String image;
private String name;
private BigDecimal price;
private Integer score;
@Transient
@OneToMany(mappedBy = "id.product")
private Set<Item> items = new HashSet<>();
public Product() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
// pega a lista de carrinhos onde o produto participou
@Transient
public Set<ShoppingCart> getCarts() {
Set<ShoppingCart> carts = new HashSet<>();
for (Item item : items) {
carts.add(item.getCart());
}
return carts;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Product product = (Product) o;
return id.equals(product.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
Item:
package com.supera.games.domain.model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Objects;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.transaction.Transactional;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.supera.games.domain.model.pk.CartItemPK;
@Entity
@Table(name = "tb_cart_item")
public class Item implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
private final CartItemPK id = new CartItemPK();
private Integer quantity;
private BigDecimal shipping;
private BigDecimal price;
public Item() {
}
// public Item(ShoppingCart cart, Product product, Integer quantity, BigDecimal price) {
public Item(ShoppingCart cart, Product product, Integer quantity) {
id.setCart(cart);
id.setProduct(product);
this.quantity = quantity;
this.shipping = new BigDecimal("10.00");
this.price = product.getPrice();
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public BigDecimal getShipping() {
return shipping;
}
public void setShipping(BigDecimal shipping) {
this.shipping = shipping;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
@JsonIgnore
public ShoppingCart getCart() {
return id.getCart();
}
public void setCart(ShoppingCart cart) {
id.setCart(cart);
}
public Product getProduct() {
return id.getProduct();
}
public void setProduct(Product product) {
id.setProduct(product);
}
@Transactional
public BigDecimal getTotalValue() {
BigDecimal qnt = BigDecimal.valueOf(quantity);
return qnt.multiply(price);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Item item = (Item) o;
return id.equals(item.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
ShoppingCart:
package com.supera.games.domain.model;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.*;
import java.math.BigDecimal;
import java.time.OffsetDateTime;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
@Entity
public class ShoppingCart {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private OffsetDateTime createdAt;
// @Transient
@OneToMany(mappedBy = "id.cart", fetch = FetchType.LAZY)
private Set<Item> items = new HashSet<>();
public ShoppingCart() {
}
public ShoppingCart(OffsetDateTime createdAt) {
this.createdAt = createdAt;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public OffsetDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(OffsetDateTime createdAt) {
this.createdAt = createdAt;
}
public Set<Item> getItems() {
return items;
}
public void setItems(Set<Item> items) {
this.items = items;
}
@Transactional
public BigDecimal subtotal() {
return null;
}
@Transactional
public BigDecimal total() {
return null;
}
@Transactional
public BigDecimal totalShipping() {
return null;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ShoppingCart cart = (ShoppingCart) o;
return id.equals(cart.id) && createdAt.equals(cart.createdAt);
}
@Override
public int hashCode() {
return Objects.hash(id, createdAt);
}
}
Item PK:
package com.supera.games.domain.model.pk;
import java.io.Serializable;
import java.util.Objects;
import javax.persistence.Embeddable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.supera.games.domain.model.Product;
import com.supera.games.domain.model.ShoppingCart;
import lombok.Getter;
import lombok.Setter;
@Embeddable
@Getter
@Setter
public class CartItemPK implements Serializable {
private static final long serialVersionUID = 1L;
@ManyToOne
@JoinColumn(name = "cart_id")
private ShoppingCart cart;
@ManyToOne
@JoinColumn(name = "product_id")
private Product product;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CartItemPK carItemPK = (CartItemPK) o;
return cart.equals(carItemPK.cart) && product.equals(carItemPK.product);
}
@Override
public int hashCode() {
return Objects.hash(cart, product);
}
}
E testei o mapeamento salvando e recuperando com algo assim: CartService:
public ShoppingCart saveItem(Item item) {
Optional<Product> product = productRepository.findById(item.getProduct().getId());
ShoppingCart cart = new ShoppingCart(OffsetDateTime.now());
ShoppingCart ct = cartRepository.save(cart);
Item it = new Item(ct, product.get(), item.getQuantity());
Item i = itemRepository.save(it);
ct.getItems().add(i);
ShoppingCart obj = cartRepository.save(ct);
return obj;
}
public List<ShoppingCart> getAllCarts() {
// get all carts
List<ShoppingCart> carts = cartRepository.findAll();
return carts;
}