POST-запрос: как записать данные в таблицу из select? Spring boot + freemarker
Есть две таблицы: Doctor с личными данными и Speciality с названием специальностей, связаны они через speciality_id в таблице Doctor При создание нового аккаунта для доктора специальность выбирается из списка select и выдаёт ошибку при сохранении. Не понимаю, как мне реализовать запоминание выбора из select и записать speciality_id в таблицу Doctor?
Controller
@GetMapping("/profile")
public String getProfile(Model model, @AuthenticationPrincipal User user, Personal personal) {
model.addAttribute(user);
model.addAttribute("personal", userService.findBio(user));
model.addAttribute("specialities", userService.specialityList());
return "user-profile";
}
@PostMapping("/activate/{id}")
public String doctorUser(@PathVariable("id") Long id, Doctor doctor, Speciality speciality) {
userService.createDoctor(id, doctor, speciality);
return "redirect:/users";
}
UserService
public List<Speciality> specialityList(){
return specialityRepository.findAll();
}
public void createDoctor(Long id, Doctor doctor, Speciality speciality) {
User user = userRepository.findById(id).orElse(null);
doctor.setUser(user);
doctor.setSpeciality(specialityRepository.getById(speciality.getId()));
doctorRepository.save(doctor);
user.getRole().clear();
user.getRole().add(Role.DOCTOR);
userRepository.save(user);
}
HTML
<form action="/activate/${user.id}" method="post">
<div class="select_wrp">
<select class="js-select2" name="speciality" placeholder="Выберите специальность">
<option value=""></option>
<#list specialities as speciality>
<option value="speciality">${speciality.name}</option>
</#list>
</select><br><br>
</div>
<input type="hidden" name="_csrf" value="${_csrf.token}">
<input type="submit" value="Активировать"/>
</form>
Speciality
Entity
@Table(name ="speciality")
public class Speciality {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name", length = 200)
private String name;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "speciality")
private List<Doctor> doctors = new ArrayList<>();
}
Doctor
@Entity
@Table(name ="doctors")
public class Doctor{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@OneToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
@JoinColumn(name = "speciality_id")
private Speciality speciality;}
Ошибка
2022-03-22 15:24:38.555 WARN 12452 --- [io-8080-exec-10] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors<EOL>Field error in object 'doctor' on field 'speciality': rejected value [speciality]; codes [typeMismatch.doctor.speciality,typeMismatch.speciality,typeMismatch.com.example.hospital.models.Speciality,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [doctor.speciality,speciality]; arguments []; default message [speciality]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.example.hospital.models.Speciality' for property 'speciality'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'speciality'; nested exception is java.lang.NumberFormatException: For input string: "speciality"]]