[英]Unable to save Entity with OneToMany mapping using JPA
我有具有One-to-Many
關系的Order
和OrderLineItem
。 當我保存訂單時,我收到 ConstraintViolationException。 下面是代碼片段。
@Entity
@Table(name = "orders")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Order extends AuditModel {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "order_id")
@JsonProperty("order_id")
private long orderId;
private double price;
@OneToMany(mappedBy = "order",
fetch = EAGER,
cascade = CascadeType.ALL )
private Set<OrderLineItem> orderLineItems = new HashSet<>();
// scaffolding code
public void addOrderLineItem(OrderLineItem orderLineItem){
this.orderLineItems.add(orderLineItem);
orderLineItem.setOrder(this);
}
... setters, getters, toString, equals and hashcode methods
}
按訂單行項目OrderLineItem
@Entity
@Table(name = "order_line_item")
@JsonIgnoreProperties(ignoreUnknown = true)
public class OrderLineItem extends AuditModel {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private double price;
@ManyToOne()
@JoinColumn(name = "order_id", nullable = false)
@JsonIgnore
private Order order;
public OrderLineItem(String name, double price){
this.name = name;
this.price = price;
}
public OrderLineItem(){}
... setters, getters, toString, equals and hashcode methods
}
OrderServiceImple class
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderRepository orderRepository;
@Override
public Order createOrder(Order order) {
System.out.println("Inside the save method of Order service .... :: ");
System.out.println(order);
return this.orderRepository.save(order);
}
...
}
訂單倉庫
@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
List<Order> findAll();
}
我正在使用OrderRepository
和OrderItemRepository
JPA 接口。
發帖請求
{
"price": 4500,
"orderLineItems": [
{
"name": "new Order Item",
"price": 4000
}
]
}
錯誤:
java.sql.SQLIntegrityConstraintViolationException: Column 'order_id' cannot be null
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117) ~[mysql-connector-java-8.0.19.jar:8.0.19]
我哪里錯了?
JPA 沒有在orderLineItems
中找到Order
,這就是為什么order_id
設置為null
的原因。 要在雙向關系中保存與父級的子級,在子級實體中設置父級也要同步雙方。
public Order createOrder(Order order) {
for(OrderLineItem orderLineItem : order.getOrderLineItems()) {
orderLineItem.setOrder(order);
}
return this.orderRepository.save(order);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.