我正在寻找在 Thymeleaf 表单中管理一对多关系的解决方案。我正在运行 Spring Boot 和 Hibernate 。
我想在提交用户信息时发布我的子对象的值,该对象是地址类型,我不知道如何在百里香中绑定它。我还应该提醒一下,在目前的表单中,我只想在提交用户表单时添加一个地址值。我想做这样的事情:
<div class="form-group">
<div class="col-sm-9">
<input type="text" th:field="*{addresses[].address.addressDesc}" placeholder="Password" class="form-control" />
<label th:if="${#fields.hasErrors('addresses')}" th:errors="*{addresses}" class="validation-message"></label>
</div>
</div>
我的用户实体:
...
/** Field to store username */
@Column(name = "username", nullable = false, length = 45)
@NotEmpty(message = "*Please provide your name")
private String username;
/** Many to many relationship with address via user_address */
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "user_address", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "address_id"))
private Set<Address> addresses = new HashSet<Address>(0);
...
我的地址实体:
public class Address implements java.io.Serializable {
/** Primary key address id */
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "address_id", unique = true, nullable = false)
private Integer addressId;
/** Field to store actual address */
@Column(name = "address_desc", nullable = false, length = 100)
private String addressDesc;
/** From Date for which the address was in use */
@Temporal(TemporalType.DATE)
@Column(name = "from_date", nullable = false, length = 10)
private Date fromDate;
/** Field to store the date till address was in use */
@Temporal(TemporalType.DATE)
@Column(name = "to_date", nullable = false, length = 10)
private Date toDate;
/** user_address entity mapping */
@OneToMany(fetch = FetchType.LAZY, mappedBy = "address")
private Set<UserAddress> userAddresses = new HashSet<UserAddress>(0);
...
}
有没有办法可以将它绑定到单个文本字段?
答案 0 :(得分:0)
在addresses
为Set
时,实际上并没有很好的方法,因为无法引用Set
内的特定项目。如果您可以改为使用List
(或者在User和List之间添加额外的getter / setter,那么只需在输入上正确设置th:field
。
th:field
属性首先需要使用数组表示法addresses[0]
引用列表中的第一项,然后您在该地址中使用addressDesc
:
th:field="*{addresses[0].addressDesc}"
答案 1 :(得分:0)
您必须像这样设置th:field
:
<div th:each="address, iterstat: ${user.addresses}">
<input th:field="*{addresses[__${iterstat.index}__].addressDesc}"/>
</div>