JPA 通过 ID 查找对象
JPA find object by ID
我有 4 个 类:
Employee.java
@Entity
class Employee {
private @Id @GeneratedValue long id;
private String firstName;
private String lastName;
private String role;
public Employee () {}
public Employee(String firstName, String lastName, String role) {
this.firstName = firstName;
this.lastName = lastName;
this.role = role;
}
}
和
Order.java
@Entity
public class Order {
private @Id @Column @GeneratedValue long id;
private String title;
private String description;
@OneToMany(fetch = FetchType.EAGER)
private List<Employee> contributors;
public Order() {
}
public Order(String title, String description) {
this.title = title;
this.description = description;
this.contributors = new ArrayList<Employee>();
}
}
LoadDatabase.java
@Configuration
public class LoadDatabase {
private static final Logger log = LoggerFactory.getLogger(LoadDatabase.class);
@Bean
CommandLineRunner initDatabase(EmployeeRepository employeeRepository, OrderRepository orderRepository) {
return args -> {
employeeRepository.save(new Employee("Name1", "lastName1", "Role1"));
employeeRepository.save(new Employee("Name2", "lastName2", "Role2"));
employeeRepository.findAll().forEach(employee -> log.info("Preloaded " + employee));
orderRepository.save(new Order("Order1", "description1"));
orderRepository.save(new Order("Order2", "description2"));
orderRepository.findAll().forEach(order -> log.info("Preloaded " + order));
}
}
OrderController.java
@RestController
public class OrderController {
private final OrderRepository orderRepository;
private final OrderModelAssembler assembler;
public OrderController(OrderRepository orderRepository, OrderModelAssembler assembler) {
this.orderRepository = orderRepository;
this.assembler = assembler;
}
@PutMapping("/order/{id}/assign/{employeeId}")
public ResponseEntity<?> assign(@PathVariable long id, @PathVariable long employeeId) {
Order order = orderRepository.findById(id) //
.orElseThrow(() -> new OrderNotFoundException(id));
return ResponseEntity //
.status(HttpStatus.METHOD_NOT_ALLOWED) //
.header(HttpHeaders.CONTENT_TYPE, MediaTypes.HTTP_PROBLEM_DETAILS_JSON_VALUE) //
.body(Problem.create() //
.withTitle("Method not allowed") //
.withDetail("You can't add person to the order that is already in a team working on it."));
}
我想将最后一个函数赋值():
- 如果存在,则按 ID“employeeId”查找员工对象。
- 检查他是否已经在“贡献者”数组列表中。
- 如果他不是,请添加。
而且我不知道如何找到他。
有人可以帮我吗? ;D
您可以像下面这样修改 OrderControlle class
@RestController
public class OrderController {
// rest of variables here
private final EmployeeRepository employeeRepository;
private OrderController(EmployeeRepository employeeRepository, ... rest of parameters here ...) {
this.employeeRepository = employeeRepository;
// assign rest of variables here
}
@PutMapping("/order/{id}/assign/{employeeId}")
public ResponseEntity<?> assign(@PathVariable Long id, @PathVariable Long employeeId) {
Order order = orderRepository.findById(id)
.orElseThrow(() -> new OrderNotFoundException(id));
Employee employee =
employeeRepository.findById(employeeId)
.orElseThrow(() -> new
EmployeeNotFoundException(employeeId));
Collection<Employee> emps = order.getContributors()
.stream()
.filter(emp ->
employeeId.equals(emp.getId())).collect(Collectors.toUnmodifiableList());
if(emps != null && emps.isEmpty()) {
order.getContributors().add(emp);
orderRepository.saveAndFlush(order);
return ResponseEntity.ok("Person added to the order");
}
else {
return ResponseEntity //
.status(HttpStatus.METHOD_NOT_ALLOWED) //
.header(HttpHeaders.CONTENT_TYPE, MediaTypes.HTTP_PROBLEM_DETAILS_JSON_VALUE) //
.body(Problem.create() //
.withTitle("Method not allowed") //
.withDetail("You can't add person to the order that is already in a team working on it."));
}
}
}
我有 4 个 类:
Employee.java
@Entity
class Employee {
private @Id @GeneratedValue long id;
private String firstName;
private String lastName;
private String role;
public Employee () {}
public Employee(String firstName, String lastName, String role) {
this.firstName = firstName;
this.lastName = lastName;
this.role = role;
}
}
和 Order.java
@Entity
public class Order {
private @Id @Column @GeneratedValue long id;
private String title;
private String description;
@OneToMany(fetch = FetchType.EAGER)
private List<Employee> contributors;
public Order() {
}
public Order(String title, String description) {
this.title = title;
this.description = description;
this.contributors = new ArrayList<Employee>();
}
}
LoadDatabase.java
@Configuration
public class LoadDatabase {
private static final Logger log = LoggerFactory.getLogger(LoadDatabase.class);
@Bean
CommandLineRunner initDatabase(EmployeeRepository employeeRepository, OrderRepository orderRepository) {
return args -> {
employeeRepository.save(new Employee("Name1", "lastName1", "Role1"));
employeeRepository.save(new Employee("Name2", "lastName2", "Role2"));
employeeRepository.findAll().forEach(employee -> log.info("Preloaded " + employee));
orderRepository.save(new Order("Order1", "description1"));
orderRepository.save(new Order("Order2", "description2"));
orderRepository.findAll().forEach(order -> log.info("Preloaded " + order));
}
}
OrderController.java
@RestController
public class OrderController {
private final OrderRepository orderRepository;
private final OrderModelAssembler assembler;
public OrderController(OrderRepository orderRepository, OrderModelAssembler assembler) {
this.orderRepository = orderRepository;
this.assembler = assembler;
}
@PutMapping("/order/{id}/assign/{employeeId}")
public ResponseEntity<?> assign(@PathVariable long id, @PathVariable long employeeId) {
Order order = orderRepository.findById(id) //
.orElseThrow(() -> new OrderNotFoundException(id));
return ResponseEntity //
.status(HttpStatus.METHOD_NOT_ALLOWED) //
.header(HttpHeaders.CONTENT_TYPE, MediaTypes.HTTP_PROBLEM_DETAILS_JSON_VALUE) //
.body(Problem.create() //
.withTitle("Method not allowed") //
.withDetail("You can't add person to the order that is already in a team working on it."));
}
我想将最后一个函数赋值():
- 如果存在,则按 ID“employeeId”查找员工对象。
- 检查他是否已经在“贡献者”数组列表中。
- 如果他不是,请添加。
而且我不知道如何找到他。 有人可以帮我吗? ;D
您可以像下面这样修改 OrderControlle class
@RestController
public class OrderController {
// rest of variables here
private final EmployeeRepository employeeRepository;
private OrderController(EmployeeRepository employeeRepository, ... rest of parameters here ...) {
this.employeeRepository = employeeRepository;
// assign rest of variables here
}
@PutMapping("/order/{id}/assign/{employeeId}")
public ResponseEntity<?> assign(@PathVariable Long id, @PathVariable Long employeeId) {
Order order = orderRepository.findById(id)
.orElseThrow(() -> new OrderNotFoundException(id));
Employee employee =
employeeRepository.findById(employeeId)
.orElseThrow(() -> new
EmployeeNotFoundException(employeeId));
Collection<Employee> emps = order.getContributors()
.stream()
.filter(emp ->
employeeId.equals(emp.getId())).collect(Collectors.toUnmodifiableList());
if(emps != null && emps.isEmpty()) {
order.getContributors().add(emp);
orderRepository.saveAndFlush(order);
return ResponseEntity.ok("Person added to the order");
}
else {
return ResponseEntity //
.status(HttpStatus.METHOD_NOT_ALLOWED) //
.header(HttpHeaders.CONTENT_TYPE, MediaTypes.HTTP_PROBLEM_DETAILS_JSON_VALUE) //
.body(Problem.create() //
.withTitle("Method not allowed") //
.withDetail("You can't add person to the order that is already in a team working on it."));
}
}
}