我正在使用SpringBoot 2.1.3 + JPA + Thymeleaf。当我遇到一个我可以粗略解决的小问题时,我就变得“大”了,但如果可能的话,我想做得好。
假设我有2个实体类:
@Entity
@Data
@Table(name = "Users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
private String nome;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "user_id", referencedColumnName = "id")
private Address address;
}
然后:
@Entity
@Data
@Table(name = "ADDRESS")
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
private String descrizione;
@OneToOne(mappedBy = "address")
private User user;
}
现在我有一个控制器可以加载数据库中存在的所有地址
@GetMapping("/showForm")
public String showUserForm(Model model) {
model.add("addresses", addressRepository.findAll());
model.add("user", new User());
}
胸腺页:
.....
<form id="form" action="" th:action="@{/save-user}" th:object="${user}" method="post">
<select th:field="*{address}" id="address">
<option th:each="add : ${addresses}" th:value="${add.id}" th:text="${add.description}"></option>
</select>
<input type="submit"></input>
</form>
.....
当我提交JPA表单时,从他的is ID值中检索地址对象。但是,如果我建立链接UserDTO和AddressDTO的表单,则无法从选择框中检索到AddressDTO对象,而只能从一个ID值中获取。
我无法在表单内部使用该实体,因为有4个选项可提供文件上传功能,并且在实体内部,我对此4个属性具有byte []类型,而在我的DTO MultipartFile中具有这种类型。
有没有办法用DTO做同样的事情? 谢谢