我是Spring/Java EE的新手,我正在尝试一些教程。 我有两个实体类,User和UserType。 我想创建并保存一个用户。 UserType是创建表单中的一个下拉列表。 你能告诉我如何在创建用户的时候保存UserType吗?Spring MVC:如何发布相关的实体对象并保存在数据库中?
- 我应该将它作为UserType对象传递吗?
- 我应该只传递UserType的id(Integer)吗?
(只显示下面的代码作为一个例子,它没有完成) 正如你可以看到下面,用户有一个叫做用户类型
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@OneToOne
private UserType type;//one to one
}
public class UserType {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
}
//HTML code for the UserType dropdown
<select th:field="*{type}">
<option th:each="type : ${types}" th:text="${type.name}" th:value="${type.id}"></option>
</select>
//Controller save user code
user.setType(new UserType(Integer.parseInt(type), ""));
this.userRepo.save(user);
财产当我尝试运行此我得到“无法将类型'java.lang.String'的属性值转换为属性'type'错误所需的类型'UserType'。
保存具有上述关系的实体的最佳方式是什么?学习这个的资源 非常感谢!
你应该通过用户类型的'id'然后在'service'或''通过id' controller'找到用户类型,并设置它'用户'。 –