【问题标题】:How to add to list of child object in Thymeleaf/Spring Boot post request如何添加到 Thymeleaf/Spring Boot 发布请求中的子对象列表
【发布时间】:2017-10-20 01:54:48
【问题描述】:

我正在寻找一种解决方案来管理 Thymeleaf 表单中的一对多关系。我正在运行 Spring BootHibernate

我想在提交用户信息时发布一个地址类型的子对象的值,但我不知道如何在百里香中绑定它。我还应该提醒一下,在当前表单中,我只想在提交用户表单时添加一个地址值。我想做这样的事情:

<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);

    ...

}

有没有办法可以将它绑定到单个文本字段?

【问题讨论】:

    标签: hibernate spring-boot thymeleaf


    【解决方案1】:

    addressesSet 时,没有真正的好方法可以做到这一点,因为无法引用Set 中的特定项目。如果您可以使用 List 代替(或向用户添加一个额外的 getter/setter 以在 Set 和 List 之间转换),那么这只是在输入上正确设置 th:field 的一种情况。

    th:field 属性首先需要使用数组表示法addresses[0] 引用列表中的第一项,然后您在该地址中使用addressDesc

    th:field="*{addresses[0].addressDesc}"
    

    【讨论】:

      【解决方案2】:

      你必须像这样设置th:field

      <div th:each="address, iterstat: ${user.addresses}">
          <input th:field="*{addresses[__${iterstat.index}__].addressDesc}"/>
      </div>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-15
        • 2017-10-20
        • 2017-09-12
        • 1970-01-01
        • 2023-03-06
        • 2017-06-21
        • 2018-02-25
        • 1970-01-01
        相关资源
        最近更新 更多