Home > Software engineering >  JPA find object by ID
JPA find object by ID

Time:03-20

I have 4 classes:

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;
    }

}

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

I want to make this last function assign():

  • Find Employee Object by id "employeeId" if exists.
  • Check if he is already in "contributors" array list.
  • add if he's not.

And i don't know how to find him. Could someone please help me? ;D

CodePudding user response:

You can modify OrderControlle class like the following

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