JPA 按 ID 查找對象

創意v

我有 4 節課:

僱員.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>();
    }
}

加載數據庫.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));
    }
}

訂單控制器.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."));
    }

我想讓最後一個函數assign():

  • 如果存在,則通過 id "employeeId" 查找員工對象。
  • 檢查他是否已經在“貢獻者”數組列表中。
  • 如果他不是,請添加。

而且我不知道怎麼找到他。有人可以幫我嗎?;D

蘇漢姆

您可以像下面這樣修改 OrderControlle 類

@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."));
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章