gpt4 book ai didi

java - thymeleaf 中的嵌套对象

转载 作者:行者123 更新时间:2023-11-30 10:41:05 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com