Mình đang làm 1 trang thêm 1 lớp học’
Domain
@Entity
@Table
@Data
public class Classes implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(length = 50)
@NotNull
private String name;
@OneToMany(mappedBy = "classes", cascade = CascadeType.ALL)
private Set<Info> infoStudents;
}
DTO
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ClassDto implements Serializable {
private Integer id;
private String name;
private Boolean isEdit;
}
Controller
@GetMapping("add")
public String addOrEdit(ModelMap model, Classes classes,ClassDto dto) {
dto.setIsEdit(false);
model.addAttribute("classes", dto);
return "admin/class/addOrEdit";
}
@PostMapping("saveOrUpdate")
public ModelAndView saveOrUpdate(ModelMap model,@Valid @ModelAttribute("classes")ClassDto classDto
, Classes entity,BindingResult result) {
if(result.hasErrors())return new ModelAndView("/admin/class/addOrEdit");
BeanUtils.copyProperties(classDto, entity);
classService.save(entity);
model.addAttribute("message", "Save Success!");
return new ModelAndView("redirect:/admin/class/");
}
HTML
<form th:action="@{/admin/class/saveOrUpdate}" method="post" th:object="${classes}" enctype="multipart/form-data">
<h2 th:text="${classes.isEdit ? 'Edit Class' : 'Add New Class'}">Add New Class</h2>
<input type="hidden" th:field="*{isEdit}">
<div th:if="${classes.IsEdit}">
<label class="form-label">Id</label>
<input type="text" class="form-control" aria-describedby="classIdHid" placeholder="Id" th:field="*{id}" readonly="readonly">
<small id="classIdHid" class="form-text text-muted">Class Id is required</small>
</div>
<div class="mb-3">
<label class="form-label">Name</label>
<input type="text" class="form-control" placeholder="name" th:field="*{name}" aria-describedby="classNameHid">
<small id="classNameHid" class="form-text text-muted">Class Name is required</small>
</div>
<div class="mb-3">
<button class="btn btn-primary" th:text="${classes.isEdit ? 'Update' : 'Save'}">Save</button>
<button><a th:href="@{/admin/class/ }">Back</a></button>
</div>
</form>
và khi nhập dữ liệu nó báo lỗi
Resolved [org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'com.example.demo.model.ClassDto' to required type 'com.example.demo.domain.Classes'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'com.example.demo.model.ClassDto' to required type 'com.example.demo.domain.Classes': no matching editors or conversion strategy found]