【发布时间】:2020-01-29 21:33:55
【问题描述】:
我正在努力解决一个问题 - 以一个 Thymeleaf 形式创建两个对象的正确(和有效)方法是什么。我尝试了 Google 提供的大量解决方案,但找不到可行的解决方案。
我有三个模型和两个超类:
超类 1:
// Lots of Lombok annotations
public class BaseEntity implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
protected Long id;
public boolean isNew() {
return this.id == null;
}
}
超类 2:
// Lots of Lombok annotations
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "type")
public class Ingredient extends BaseEntity {
@Column(name="name")
protected String name;
@OneToMany(mappedBy = "ingredient")
private Set<BatchIngredient> batches = new HashSet<>();
}
批量模型:
// Lots of Lombok annotations
public class Batch extends BaseEntity {
//fields, getters, setter...
@OneToMany(mappedBy = "batch")
private Set<BatchIngredient> ingredients = new HashSet<>();
}
麦芽模型:
// Lots of Lombok annotations
public class Malt extends Ingredient {
//fields, getters, setter...
}
BatchIngredient 模型 - Batch 和 Ingredients 之间的关联:
// Lots of Lombok annotations
@Table(name="batch_ingredient")
@IdClass(BatchIngredientId.class)
public class BatchIngredient {
@Id
private Long ingredientId;
@Id
private Long batchId;
@Id
@Column(name="amount")
private int amount;
@Id
@Column(name = "way_of_serving")
private String wayOfServing;
@ManyToOne
@JoinColumn(name = "ingredientId", updatable = false, insertable = false, referencedColumnName = "id")
private Ingredient ingredient;
@ManyToOne
@JoinColumn(name = "batchId", updatable = false, insertable = false, referencedColumnName = "id")
private Batch batch;
}
我正在使用批处理控制器输入表单:
@Controller
@RequestMapping("/batch")
class BatchController {
@ModelAttribute("malts")
public Set<Malt> populateMalts() {
return maltService.findByOrderByNameAsc();
}
@GetMapping("/new")
public String initCreationForm(Model model) {
model.addAttribute("batch", new Batch());
model.addAttribute("batchIngredient", new BatchIngredient());
return VIEWS_BATCH_CREATE_OR_UPDATE_FORM;
}
// other methods...
}
这个表格用来填充一些 Batch 数据:
<body>
<form th:action="@{'/batch/saveBatch'}" method="post">
<input type="hidden" name ="id" th:field="*{batch.id}">
<label>Batch number:</label>
<input type="text" class="form-control" th:field="*{batch.batchNumber}"/>
// lots of other input fields to populate Batch model...
And here we have table in the form - here a I want to create "BatchIngredient" object, and in this example - pass to this object "Malt" from the drop-down field
<table class="table">
<thead class="thead">
<tr>
<th>Name</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr th:remove="all">
<td>Pale Ale</td>
<td>4000</td>
</tr>
<tr>
<td>
<select class="form-control" th:value="*{malt.id}">
<option th:each="malt : ${malts}"
th:value="${malt?.id}"
th:text="${malt?.name}">
</option>
</select>
</td>
</tr>
</tbody>
</table>
<button class="submit-button" type="submit">Submit</button>
</form>
</body>
我不知道如何实现这一点,或者是否有可能。有什么建议吗?
【问题讨论】:
标签: spring model-view-controller thymeleaf