I am creating a simple webapp with CRUD. However I am stuck with the create method, when ever I am creating a Host, I get ConstraintViolationException
because the attribute name
is null
eventhough it shouldn't be null.
Host:
@Builder
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
@Table(name = "hosts")
public class Host extends AbstractPersistable<Long> {
@Getter
@NotNull
private String name;
@Getter
private String homepage;
@Getter
@ManyToMany(cascade = CascadeType.PERSIST)
private Set<Show> shows;
}
HostDto:
public class HostDto {
private String name;
private String homepage;
private Set<ShowDto> shows;
}
HostController:
@Controller
@RequestMapping(path = "/webapp/hosts")
public class HostController {
private final HostService hostService;
@RequestMapping("/new")
public ModelAndView newHost() {
ModelAndView mav = new ModelAndView("host-new");
HostDto dto = new HostDto();
mav.addObject("hostDto", dto);
return mav;
}
@PostMapping("/save")
public ModelAndView insertHost(@ModelAttribute("hostDto") HostDto hostDto) {
hostService.insert(hostDto);
return new ModelAndView("redirect:/");
}
}
thymeleaf host-list:
<h1>Hosts</h1>
<a href="/webapp/hosts/new">Create new Host</a>
thymeleaf host-new:
<h1>Create new Host</h1>
<form action="#" th:action="@{/webapp/hosts/save}" th:object="${hostDto}" method="post">
<input type="text" th:field="*{name}" id="name" placeholder="Name">
<input type="text" th:field="*{homepage}" id="email" placeholder="homepage">
<input type="submit" value="Add Host">
</form>
Exception:
javax.validation.ConstraintViolationException: Validation failed for classes [at.spengergasse.qaa18988.model.Host] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='must not be null', propertyPath=name, rootBeanClass=class at.spengergasse.qaa18988.model.Host, messageTemplate='{javax.validation.constraints.NotNull.message}'}
HostService:
public HostDto insert(HostDto host) {
return Optional.ofNullable(host)
.map(dto -> dto.toHost())
.map(entity -> hostRepository.save(entity))
.map(entity -> HostDto.valueOfHost(entity))
.get();
}
hostRepository extends the CrudRepository.
I believe that I've got the connection between HostController
and Thymeleaf
wrong, because I was debugging the insertHost()
in HostController
and all the attributes in hostDto
were null.
CodePudding user response:
Make sure you have @Setter
above your class HostDto