Reputation: 135
I'm trying to add a order with equipment list, here's my entities:
the order entity
@Entity @Table(name = "orders") public class Order extends Ticket{
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
private Set<OrderEquipment> orderEquipments = new HashSet<>();}
the equipment entity
@Entity @Table(name = "equipments") public class Equipment extends DateAudit {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Size(max = 30)
private String name;
@NotNull
private Long nbr_piece ;
@OneToMany(mappedBy = "equipment", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<OrderEquipment> orderEquipments = new HashSet<>();}
and the order_equipment entity
@Entity @Table(name = "order_equipment") public class OrderEquipment extends DateAudit { @Id
@ManyToOne
@JoinColumn(name = "order_id")
private Order order;
@Id
@ManyToOne
@JoinColumn(name = "equipment_id")
private Equipment equipment;
@NotBlank
@Column(name = "quantity")
private Long quantity;}
here is the add function in the orderController
@PostMapping("/orders")
public Order createOrder(@Valid @RequestBody Order Order){
Order.setObservateurEmail(Order.getObservateurEmail());
Order.setObject(Order.getObject());
Order.setDescription(Order.getDescription());
return orderRepository.save(Order);
}
Upvotes: 2
Views: 4488
Reputation: 741
I have seen a mistakes there, lemme try to help you. Since you issue is not clear, please lemme know if it does/does not work:
You have two bidirectional mappings there:
You are using @JoinColumn for both of them, even though they are bidirectional. Please take a look at this. You should always use the mappedBy
attribute when defining bidirectional relationships.
Now, you are receiving an Order object from a POST request, making changes to 3 attributes and then saving it. Since the mapping between the Order
and OrderEquipment
have the CascadeType.ALL
attribute, any save on the Order object will save all OrderEquipment children associated. If the Order object you are receiving already have OrderEquipment children, your method will also save/update them.
Your POST mapping looks good to me, just take care with your table relationship definitions.
Take a look at this answer to check how a lits of entities should be formatted on a JSON POST.
Upvotes: 1