使用包裹服务进行项目。我创建了OrderItem API和Dispatcher API。现在,我想通过关系建立联系。这个想法是:调度程序可以有许多orderItems。 OrderItem只能有一个调度程序。如果删除调度员,则他的订单项也必须出去。我已经创建了一些内容,但是我在这里太混乱了,无法在逻辑上完成此操作。有人会给我一些有关如何解决这个问题的想法。
我是否需要将双方关系或只放在其中之一?
我何时需要使用参数创建构造函数?因为在实体类中,您不必具有arg构造函数...?
OrderItem类:
@Entity
public class OrderItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@NotBlank(message = "Order weight is required")
private String weight;
@NotBlank(message = "Order dimensions are required")
private String dimensions;
@NotBlank(message = "Order origin is required")
private String origin;
@NotBlank(message = "Order destination is required")
private String destination;
@NotNull(message = "Order comment cannot be null")
private String comment;
@ManyToOne
private Dispatcher dispatcher;
public OrderItem() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getDimensions() {
return dimensions;
}
public void setDimensions(String dimensions) {
this.dimensions = dimensions;
}
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Dispatcher getDispatcher() {
return dispatcher;
}
public void setDispatcher(Dispatcher dispatcher) {
this.dispatcher = dispatcher;
}
}
OrderController类:
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
OrderService service;
@Autowired
private MapValidationErrorService mapValidationErrorService;
@GetMapping("/{dispatcherId}/orders")
public List<OrderItem> getAllOrderItems(@PathVariable int dispatcherId) {
return service.getAllOrderItems(dispatcherId);
}
@PostMapping("/{dispatcherId}/orders")
public ResponseEntity<?> saveOrder(@Valid @RequestBody OrderItem orderItem, @PathVariable int dispatcherId, BindingResult result) {
ResponseEntity<?> errorMap = mapValidationErrorService.MapValidationService(result);
if (errorMap != null) {
return errorMap;
}
orderItem.setDispatcher(new Dispatcher(dispatcherId, "", "", ""));
service.insertOrUpdate(orderItem);
return new ResponseEntity<String>("Order was created successfully", HttpStatus.CREATED);
}
@PutMapping("/update")
public ResponseEntity<?> updateOrder(@Valid @RequestBody OrderItem orderItem, BindingResult result) {
ResponseEntity<?> errorMap = mapValidationErrorService.MapValidationService(result);
if (errorMap != null) {
return errorMap;
}
service.insertOrUpdate(orderItem);
return new ResponseEntity<String>("Order was updated successfully", HttpStatus.OK);
}
@GetMapping("/all")
public Iterable<OrderItem> getAllOrders() {
return service.findAllOrders();
}
@DeleteMapping("/{orderId}")
public ResponseEntity<String> deleteOrder(@PathVariable int orderId) {
if (service.findById(orderId) == null) {
throw new CustomErrorException("Order doesn't exist, check order id");
}
service.deleteOrder(orderId);
return new ResponseEntity<String>("Order with ID " + orderId + " was deleted", HttpStatus.OK);
}
@GetMapping("/{orderId}")
public ResponseEntity<OrderItem> getOrderById(@PathVariable int orderId) {
OrderItem item = service.findById(orderId);
if (service.findById(orderId) == null) {
throw new CustomErrorException("Order id not found - " + orderId);
}
return new ResponseEntity<OrderItem>(item, HttpStatus.OK);
}
}
调度程序类:
@Entity
public class Dispatcher {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@NotBlank(message = "Dispatcher first name is required")
private String firstName;
@NotBlank(message = "Dispatcher last name is required")
private String lastName;
@NotBlank(message = "Dispatcher email name is required")
private String email;
@NotBlank(message = "Dispatcher email is required")
private String password;
@NotBlank(message = "Dispatcher phone number is required")
private String phoneNumber;
public Dispatcher() {
}
public Dispatcher(int id, String firstName, String lastName, String email) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
DispatcherController类:
@RestController
@RequestMapping("/dispatcher")
public class DispatcherController {
@Autowired
DispatcherService service;
@Autowired
private MapValidationErrorService mapValidationErrorService;
@PostMapping("/save")
public ResponseEntity<?> saveDispatcher(@Valid @RequestBody Dispatcher dispatcher, BindingResult result) {
ResponseEntity<?> errorMap = mapValidationErrorService.MapValidationService(result);
if (errorMap != null) {
return errorMap;
}
service.insertOrUpdate(dispatcher);
return new ResponseEntity<String>("Dispatcher was created successfully", HttpStatus.CREATED);
}
@GetMapping("/all")
public Iterable<Dispatcher> getAllDispatchers() {
return service.findAllDispatchers();
}
@GetMapping("/{dispatcherId}")
public ResponseEntity<?> getDispatcherById(@PathVariable int dispatcherId) {
Dispatcher dispatcher = service.findById(dispatcherId);
if (service.findById(dispatcherId) == null) {
throw new CustomErrorException("Dispatcher id not found - " + dispatcherId);
}
return new ResponseEntity<Dispatcher>(dispatcher, HttpStatus.OK);
}
@DeleteMapping("/{dispatcherId}")
public ResponseEntity<?> deleteDispatcher(@PathVariable int dispatcherId) {
if (service.findById(dispatcherId) == null) {
throw new CustomErrorException("Dispatcher doesn't exist, check dispatcher id");
}
service.deleteDispatcher(dispatcherId);
return new ResponseEntity<String>("Order with ID " + dispatcherId + " was deleted", HttpStatus.OK);
}
@PutMapping("/update")
public ResponseEntity<?> updateDispatcher(@Valid @RequestBody Dispatcher dispatcher, BindingResult result) {
ResponseEntity<?> errorMap = mapValidationErrorService.MapValidationService(result);
if (errorMap != null) {
return errorMap;
}
service.insertOrUpdate(dispatcher);
return new ResponseEntity<String>("Dispatcher was updated successfully", HttpStatus.OK);
}
}
主要区别在于双向关系使您可以双向访问。这样您就可以在没有任何查询的情况下访问另一端。它也适用于级联操作。
双向@OneToMany
产生更好的DML,因为@ManyToOne
拥有关系。
单向@ManyToOne
或双向@OneToMany
比单向@OneToMany
更有效。
在JPA 2.0之前,此单向@OneToMany
使用联接表来管理父行和子行之间的关联。因此,读(连接3个表)和写(插入3个表)的成本更高。
由于JPA 2.0用于单向@OneToMany
,因此应将其与@JoinColumn
关联使用
使用@JoinColumn
,@OneToMany
关联控制子表FK ..,因此不需要额外的连接表。
但是在性能方面,没有比双向关联更好的了。
单向@OneToMany
的优点->简单。
关于第二个问题:仅持久性框架(例如Hibernate)才需要NoArg。但是您可以(并且应该)使用自己的构造函数来创建consistent
对象。
我认为您对关系的定义不正确。是的,您需要有no-args构造函数。从数据库中检索数据时,这有助于休眠将数据库中的值映射到Java对象]
假设您要进行单向映射,
@Entity
public class OrderItem {
@OneToMany( cascade = CascadeType.ALL )
@JoinColumn(name = <foriegn_key_column in dispatcher table i.e. id>)
private Dispatcher dispatcher;
}
@Entity
public class Dispatcher {
private List<OrderItem > orders;
}