Let me start by saying I’m fairly new to Spring Boot so apologies if I’m making a silly mistake somewhere. I am trying to retrieve the value of my form post using @RequestParam so I can utilize it in a JPA query to return kids who have a specific pet type. I’ve done other JPA queries and had successful results, but getting the Enum value from a populated select so I can pass it back to the controller query has me stumped.
I keep getting the error:
Required request parameter ‘p’ for method parameter type String is not present
I need to pass the petType to the Post method findByPet_PetTypeEquals in order to retrieve what kids have that particular pet type. I just can’t figure out how to pass that form data back to the controller.
Kid class:
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private String name; private Integer age; @OneToOne @JoinTable(name="KID_PET", joinColumns=@JoinColumn(name="KID_ID"), inverseJoinColumns=@JoinColumn(name="PET_ID")) private Pet pet;
Pet class:
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private String name; private Boolean furry; @Enumerated(EnumType.STRING) private PetType petType;
PetType Enum:
public enum PetType { DOG, CAT, FISH, BIRD, HAMSTER; }
Relevant Controller Methods:
private KidRepository kidRepo; @GetMapping("/") public String index(Model model) { model.addAttribute("kid", new Kid()); model.addAttribute("petType", PetType.values()); return "index"; } @PostMapping("/findByPet_PetTypeEquals") public String findByPet_PetTypeEquals(Model model, @RequestParam String p) { List<Kid> kidList = kidRepo.findByPet_PetTypeEquals(p); model.addAttribute("kidList", kidList); return "displayKid"; }
Form:
<form method="post" th:action="findByPet_PetTypeEquals"> Pet Type: <select th:field="*{petType}"> <option th:each="p : ${petType}" th:value="${p}" th:text="${p}"></option> </select> <button type="submit">Submit</button> </form>
Repo:
public interface KidRepository extends JpaRepository<Kid, Long>{ public List<Kid> findByAgeGreaterThan(Integer age); // DONE public List<Kid> findByPetNotNull(); // DONE public List<Kid> findByPet_PetTypeEquals(String p); // NOT DONE public List<Kid> findByPet_FurryIsTrue(); // DONE }
Any advice or guidance is greatly appreciated! Thank you.
Advertisement
Answer
as method param in findByPet_PetTypeEquals, give Enum instead of String.
@Enumerated is just an annotation that allows JPA/hibernate to store enum as string in DB and while retrieving convert string to enum. So, in your method param, it should be enum type