java - thymeleaf 中的嵌套对象

标签 java thymeleaf

我正在尝试使用 thymeleaf 构建一个表单,我的实体包括对象的集合(列表)。我正在努力为这种情况构建合适的表格。

这是我的实体:

@Entity
public class Owner {

    @Id
    @GeneratedValue
    private int id;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
    private List<Phone> phones;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
    private List<Pet> pets;

//getterss and setters

这是 Pet.class

@Entity
public class Pet {

    @Id
    @GeneratedValue
    private int id;
    @Column(name = "pet_name")
    private String petName;

    @ManyToOne
    @JoinColumn(name = "owner_Id")
    private Owner owner; 

//getters and setters

这是我用于构建表单的 html 文件:

<!DOCTYPE html>
<html xmlns:th="http:/www.thymealeaf.org">
<head>
<meta charset="ISO-8859-1"></meta>
<title>Add new owner to database</title>
</head>
<body>
    <div id="form">
        <form th:action="@{/addOwner.do}" th:object="${Owner}" method="post">

            <label for="firstName">First Name: </label> 
            <input type="text" th:field="*{firstName}" /> 

            <label for="lastName">Last Name:</label>
            <input type="text" th:field="*{lastName}" /> 

            <!-- Here is the core problem -->
            <label for="pets">Pet Name: </label>
            <input type="text" th:each="pet : *{pets}"/> 

            <input type="submit" value="add" />
        </form>
    </div>
</body>

所以我正在为此苦苦挣扎:

 <!-- Here is the core problem -->
                <label for="pets">Pet Name: </label>
                <input type="text" th:each="pet : *{pets}"/> 

我的问题是,我不知道如何访问表单内 List 集合中的 Pet 对象,以便我可以输入 petName 属性。

//edit 或者也许有不同的方法来做到这一点?显而易见的方法是从表单中获取一个字符串,然后在将对象添加到数据库之前在 Controller 中将字符串构建为宠物名称?

最佳答案

你能试试这个吗,让我知道这是否对你有用

<div th:each="pet, stat : *{pets}"> 
   <input type="text" th:field="*{pet[__${stat.index}__].petName}" /> 
</div>

关于java - thymeleaf 中的嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38635850/

相关文章:

java - 显示在java中执行了BFS遍历的图的树结构

java - 将每个字母表设置为数字

java - 检查当前类的实例时,为什么 "x instanceof getClass()"不起作用?

java - 里面有 thymeleaf [if mso]

spring - Thymeleaf 中的条件包装

javascript - thymeleaf th :text How to add static text to dynamic value

java - Lucene setPositionIncrement 不起作用

java - 参数 Java servlet Libvirt 中的 UUID

html - 如何在 thymeleaf 中将值设置为 "NULL"

include - 动态 Thymeleaf 包括