【问题标题】:Posting OneToMany database records in thymeleaf templates在百里香模板中发布 OneToMany 数据库记录
【发布时间】:2016-02-03 20:08:52
【问题描述】:

我有 2 个类 - Contact 和 Phone,Contact 类有一个 Set of Phones 。 这是我的控制器

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class ContactFormController {

@Autowired
ContactRepository contactRepo;

@Autowired
PhoneRepository phoneRepo;

@RequestMapping(value = "/data", method = RequestMethod.GET)
public String showAll(Model model) {
    model.addAttribute("contacts", contactRepo.findAll());
    model.addAttribute("phones",  phoneRepo.findAll());
    return "dataresult";
}

我想通过 thymeleaf 模板显示我的数据库记录,这是我的 html 代码:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Dane</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h3>Dane</h3>
<p th:each="contact : ${contacts}">
    <h4>ID:</h4>
    <div th:text="${contact.id}"></div>
    <h4>Name:</h4>
    <div th:text="${contact.firstName}"></div>
    <li th:each="item : ${contact.phones}" th:text="${item}">Item description   here...</li>
    <div>---------</div>
</p>
</body>
</html>

这是我得到的结果 - http://i.imgur.com/pPIA5ma.png 电话课-http://pastebin.com/L6Sqsp9q 接触类有一个 @OneToMany(fetch = FetchType.LAZY) @JoinColumn(name = "contactId") 私人设置电话;

如何让我的控制器显示联系人 ID、姓名和电话号码集?

【问题讨论】:

  • @ChiefTwoPencils 我不知道该怎么做,我对 thymeleaf 和 html 完全是菜鸟。虽然我认为我必须以某种方式访问​​电话类上的数字字段,但我不知道如何
  • 忽略最后一条评论,我看不出问题出在哪里。

标签: java spring thymeleaf


【解决方案1】:

您所拥有的是打印 Phone 本身来解释您的输出。您需要做的是访问itemnumber 字段。例如,

th:each="item : ${contact.phones}" th:text="${item.number}"

或者,

th:each="item : ${contact.phones}" th:text="${item.getNumber()}"

【讨论】:

  • 非常感谢!它正在工作。我想我还有一个问题,我可以在一段时间内再请你帮忙吗? :)
  • @newbie101,没问题,很高兴为您提供帮助。您可以通过接受它作为答案并给予支持来表达您的感激之情:)
  • 喜欢的话可以@我。我将在当天剩余的大部分时间里上课,但今晚晚些时候会回来查看@newbie101。
  • 好的。这是代码正在工作,它正在向基础添加一条新记录,但只有名称。 pastebin.com/py11UTWm 我不知道如何制作输入数字的表格。这是 html - pastebin.com/qQxKdZqQ
  • @newbie101,您需要另一个输入 (&lt;input type="text" th:field="*{firstName}" /&gt;),但要输入数字。如果您有一个不按“家庭”、“工作”或类似名称区分的号码列表,则需要有一种动态方式来根据请求添加另一个号码。
猜你喜欢
  • 2015-11-29
  • 2019-12-19
  • 2015-06-01
  • 2013-02-03
  • 1970-01-01
  • 2019-03-17
  • 2021-04-01
  • 1970-01-01
  • 2019-04-16
相关资源
最近更新 更多