I've got 2 classes - Contact and Phone, class Contact has a Set of Phones . Here's mine controller
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";
}
I want to display records of my database through thymeleaf template, here's my html code :
<!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>
Here's what I've got as result - https://i.sstatic.net/wgeqK.png Phone class - http://pastebin.com/L6Sqsp9q Contact class has a @OneToMany(fetch = FetchType.LAZY) @JoinColumn(name = "contactId") private Set phones;
How can i make my controller to display Contact id, name AND Set of phone numbers ?
What you have there is printing the Phone itself which explains your output. What you need to do is access the number field of the item. For example,
th:each="item : ${contact.phones}" th:text="${item.number}"
or,
th:each="item : ${contact.phones}" th:text="${item.getNumber()}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With