假设我有一个实体:
@Entity
@Table(name = "Building")
@Data
public class Building {
@Id
@Column(name = "buildingId")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer buildingId;
@OneToOne(cascade = {CascadeType.MERGE}
@JoinColumn(name = "buildingType")
private BuildingType buildingType;
//...
}
在我的控制器中,我将所有建筑物类型都放入了模型:
@RequestMapping("/addBuilding")
public String newBuilding(Model model, @ModelAttribute Building building){
model.addAttribute("buildingTypes", buildingTypeService.getBuildingTypes()); //gives me an ArrayList<BuildingType>
}
现在我要遍历建筑物类型以将其放入下拉<select>
:
<form class="some-form" method="post" th:action="@{/addBuilding}">
<select id="type" class="some-class" required>
<option th:each="buildingType : ${buildingTypes}" th:text="${buildingType.name}"></option>
</select>
<button type="submit" class="button">Store</butto>
</form>
这很好。但是,当我尝试获取所选的建筑物类型时:
<form class="some-form" method="post" th:action="@{/addBuilding}" th:object="${building}">
<select id="type" class="some-class" th:field="*{buildingType}" required>
<option th:each="buildingType : ${buildingTypes}" th:value="${buildingType}" th:text="${buildingType.name}"></option>
</select>
<button type="submit" class="button">Store</button>
</form>
我的控制器没有收到对象,而是一个字符串:
@RequestMapping("/addBuilding")
public String newBuilding(Model model, @ModelAttribute Building building){
//...
System.out.println((building.getBuildingType() instanceof BuildingType)); //false
}
是否可以从Thymeleaf获取对象?还是有必要为BuildingType创建一个原始的瞬态字段(例如String),从Thymeleaf返回它,并基于该字段在控制器中搜索BuildingType?