I am trying to select two columns which are in two separate tables. One table is users and other one is privillages. I need to fetch username from users and pname from privillages. My model classes are like follows,
#Entity
#Table(name = "users")
public class Users implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
public String username;
public String password;
public Integer privid;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "pid")
private Collection<Privillages> priviJoin;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "privid")
public Integer getPrivid() {
return privid;
}
public void setPrivid(Integer privid) {
this.privid = privid;
}
public Collection<Privillages> getPriviJoin() {
return priviJoin;
}
public void setPriviJoin(Privillages priviJoin) {
this.priviJoin = (Collection<Privillages>) priviJoin;
}
public Users() {
}
#Override
public String toString() {
return String.format("Users[id=%d, username='%s', password='%s']", id,
username, password);
}
}
And my Privillages class is,
#Entity
#Table(name = "privillages")
public class Privillages implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Integer id;
public String pname;
#ManyToOne(optional = false)
#JoinColumn(name = "pid", referencedColumnName = "privid")
public Users pid;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "pname")
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
#Column(name = "pid")
public Users getPid() {
return pid;
}
public void setPid(Users pid) {
this.pid = pid;
}
public Privillages(){
}
}
And my Users repository is,
public interface UsersRepository extends CrudRepository<Users, Integer>
{
#Query("select u from Users ug join ug.priviJoin u")
List<Users> findByUsername();
}
And My Privillage repository is:
public interface PrivillagesRepository extends CrudRepository<Privillages,
Integer> {
}
My controller file is:
#RequestMapping(value = "/joinResult", method = RequestMethod.GET)
public ModelAndView joinResultShow(Model model)
{
List<Privillages> privillages = (List<Privillages>)privillagesRepo.findAll();
model.addAttribute("joinData",privillages);
ModelAndView viewObj = new ModelAndView("fleethome");
return viewObj;
}
And displaying like:
<table>
<tr th:each="message : ${joinData}">
<td th:text="${message.pname}"></td>
<td th:text="${message.pid.username}"></td>
</tr>
</table>
And getting error like:
There was an unexpected error (type=Internal Server Error, status=500).
No message available
Stacktrace is:
java.lang.NullPointerException: null
at
com.central.controller.WebController.joinResultShow(WebController.java:58) ~
[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~
[na:1.8.0_141]
at sun.reflect.NativeMethodAccessorImpl.invoke
(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_141]
at sun.reflect.DelegatingMethodAccessorImpl.
invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_141]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_141]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke
(InvocableHandlerMethod.java:205) ~[spring-web-
4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.
invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-
4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.
ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.
java:97) ~[spring-webmvc-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.
RequestMappingHandlerAdapter.invokeHandlerMethod
(RequestMappingHandlerAdapter .java:827)
~[spring-webmvc-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.web.servlet.mvc.method.
annotation.RequestMappingHandlerAdapter.handleInternal
(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-
4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.
handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-
4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.
doDispatch(DispatcherServlet.java:967) ~[spring-webmvc-
4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService
(DispatcherServlet.java:901) ~[spring-webmvc-
4.3.11.RELEASE.jar:4.3.11.RELEASE]
I need to retrieve username from users and pname column from privillages. How should I change my code?
First of all, you should create privillages repository:
public interface PrivillagesRepository extends CrudRepository<Privillages, Integer> {
}
Then you can do find all privillages in your controller:
List<Privillages> privillages = privillages.findAll();
model.addAttribute("joinData",privillages);
After that, change your template:
<table>
<tr th:each="message : ${joinData}">
<td th:text="${message.pname}"></td>
<td th:text="${message.pid.username}"></td>
</tr>
</table>
As you can see, to print username, you need to use nested field "pid" (Users class)
I just explored the context that, Use the same repository as the Userrepository along with the JPQL query. And modify the view file according to that for displaying username with using the pid from Privillages Model class. I am adding the code need to modify with certain changes.
My controller file is,
UsersRepository userRepo;
#RequestMapping(value = "/joinResult", method = RequestMethod.GET)
public ModelAndView joinResultShow(Model model)
{
List<Users> use = (List<Users>) userRepo.findByUsername();
model.addAttribute("joinData",use);
ModelAndView viewObj = new ModelAndView("fleethome");
return viewObj;
}
And the repository ,
public interface UsersRepository extends CrudRepository<Users, Integer>
{
Users findByUsernameAndPassword(String username,String password);
#Query("select u from Users ug join ug.priviJoin u")
List<Users> findByUsername();
}
And My Privillage repository,
public interface PrivillagesRepository extends CrudRepository<Privillages,
Integer> {
}
And modify the View file with,
<table>
<th> Username </th>
<th> Privillage Name </th>
<tr th:each="message : ${joinData}">
<td th:text="${message.pid.username}"></td>
<td th:text="${message.pname}"></td>
</tr>
</table>
Related
I am a beginner of spring boot application. I want to join the course table and the student table together. What I tried so far I attached code below. I didn't get any errors. When the student page is loaded I show course id only I need to display the name instead of the id. I attached the screenshot image below.
Above screenshot image only displayed the course id I need to display the course name.
Student Controller
#RequestMapping(value = "/student", method = RequestMethod.GET)
public String viewStudentPage(Model model) {
List<Student> liststudent = services.listAll();
model.addAttribute("liststudent", liststudent);
System.out.print("Get / ");
return "Student";
}
I made the relation the below. What I tried so far now.
Course.java
#Entity
public class Course {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String coursename;
private int duration;
#ManyToOne
private Student student;
public Course()
{
}
public Course(Long id, String coursename, int duration) {
this.id = id;
this.coursename = coursename;
this.duration = duration;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCoursename() {
return coursename;
}
public void setCoursename(String coursename) {
this.coursename = coursename;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
#Override
public String toString() {
return "Course [id=" + id + ", coursename=" + coursename + ", duration=" + duration + "]";
}
}
Student.java
#Entity
#Table(name="student")
public class Student {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String stname;
private int course;
private int fee;
#OneToMany(mappedBy = "course")
private List<Student> student;
public Student() {
}
public Student(Long id, String stname, int course, int fee) {
this.id = id;
this.stname = stname;
this.course = course;
this.fee = fee;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStname() {
return stname;
}
public void setStname(String stname) {
this.stname = stname;
}
public int getCourse() {
return course;
}
public void setCourse(int course) {
this.course = course;
}
public int getFee() {
return fee;
}
public void setFee(int fee) {
this.fee = fee;
}
#Override
public String toString() {
return "Student [id=" + id + ", stname=" + stname + ", course=" + course + ", fee=" + fee + "]";
}
}
StudentRepository
#Repository
public interface StudentRepository extends JpaRepository<Student, Long>{ }
Student.html
<table class="table">
<thead class="thead-dark">
<tr>
<th>Student ID</th>
<th>Student Name</th>
<th>Course Name</th>
<th>Fee</th>
<th>edit</th>
<th>delete</th>
</tr>
</thead>
<tbody>
<tr th:each="student : ${liststudent}">
<td th:text="${student.id}">Student ID</td>
<td th:text="${student.stname}">Student Name</td>
<td th:text="${student.course}">Course</td>
<td th:text="${student.fee}">Fee</td>
<td>
<a th:href="#{'/Student/edit/' + ${student.id}}">Edit</a>
</td>
<td>
<a th:href="#{'/Student/delete/' + ${student.id}}">Delete</a>
</td>
</tr>
</tbody>
</table>
Custom Code i wrote it to Join
#Repository
public interface StudentRepository extends JpaRepository<Student, Long>{
#Query(value="select student.id, student.stname, course.coursename from student Inner JOIN course ON student.course= course.id", nativeQuery=true)
List<Object[]> findStudent();
}
You have to add a custom query to get the course name. Your listAll() return all student object without course, the payload doesn't have any variable like name and you have course id in your entity that's why ID appearing in your UI.
Your student object have course objects also you can get like below.
you have the wrong relationship on your entity correct as below.
It should come under ManyToMany relationship because one user have many courses and one course belong to many student anyway you started as oneToMany then follow as below.
within Student Entity.
#OneToMany(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,mappedBy = "student")
private List<Course> course;
within Course entity
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "id", nullable = false)
private Student student;
then try you access the course object as below.
th:field="*{student.course.name}"
if you want to try a custom query then try to as below.
#Query(value="select s.id, s.name, c.name from Student s left JOIN Course c on student.course_id= c.id", nativeQuery=true)
List<Object[]> findStudent();
I have 2 classes. USER class & ORDER class.
Order class has User object with #ManyToOne relationship.
When the RestController retrieves the Order object post insertion of Order object using #PostMapping,it returns null value for nested User object
Rest Controller
#RestController
public class OrderController {
#PersistenceContext
EntityManager entityManager;
#Transactional
#PostMapping(value = "api/v1/create/order")
public Order createOrder(#RequestBody Order order){
entityManager.persist(order);
return order;
}
}
Order class
#Entity
#Table(name = "booking_order")
public class Order {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Integer orderID;
#Column
String transactionAmount;
#Column
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
Date bookingTimestamp;
#ManyToOne
User user;
public Order(){}
public Integer getOrderID() {
return orderID;
}
public void setOrderID(Integer orderID) {
this.orderID = orderID;
}
public String getTransactionAmount() {
return transactionAmount;
}
public void setTransactionAmount(String transactionAmount) {
this.transactionAmount = transactionAmount;
}
public Date getBookingTimestamp() {
return bookingTimestamp;
}
public void setBookingTimestamp(Date bookingTimestamp) {
this.bookingTimestamp = bookingTimestamp;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
User Class
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id;
#Column(unique = true)
String username;
#Column
String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Input JSON
{
"transactionAmount" : "100.50",
"user":{
"id":1
}
}
Order Response
{
"orderID": 1,
"transactionAmount": "100.50",
"bookingTimestamp": "2019-05-15T20:44:43.234+0000",
"user": {
"id": 1,
"username": null,
"password": null
}
}
I've a model User. There's a field which is contact and it's a non primary key. How can i fetch data using this key? it's an unique key.
This is my model.
#Entity
#Table(name = "tbl_user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id")
long userId;
#Column(name = "name")
String name;
#Column(name = "email")
String email;
#Column(name = "contact")
String contact;
#Column(name = "category")
String category;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public User() {
}
}
This is the method inside Service layer.
public User getUserByContact(String contact) {
Optional<User> result = userRepository.findByContact(contact);
User user = result.get();
return user;
}
This is the repository.
#Repository
public interface UserRepository extends JpaRepository<User, Long> {
#Query("select u from User u where u.contact = ?1")
User findByContact(String contact);
}
I'm getting an error on "select u from User u where u.contact = ?1" this portion under User and it's saying "cant resolve symbol User". Would appreciate any sort of help.
Leave out the #Query part, that part is not needed if you extend a JpaRepository. As stated in the documentation JPA derives the query from the method name.
I'm not sure whether this is an issue, but in your entity class you use a long for id and in your repository definition (JpaRepository<User, Long>) you use a Long. Correct me if this is not problematic.
If you want to use #Query, then the right approach would be to use #Param to define the variable
#Query("select u from User u where u.contact = :contactVar ", nativeQuery = true)
User findByContact(#Param("contactVar")String contactVar);
i am try to create a one to many bidirectional mapping using spring boot and spring data jpa please look the below entity
Employer Entity
#Entity
public class Employer
{
private Long id;
private String employerName;
private List<Employee> employees;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getEmployerName()
{
return employerName;
}
public void setEmployerName(String employerName)
{
this.employerName = employerName;
}
#OneToMany(cascade=CascadeType.ALL, mappedBy="employer")
public List<Employee> getEmployees()
{
return employees;
}
public void setEmployees(List<Employee> employees)
{
this.employees = employees;
}
}
Employee Entity
#Entity
public class Employee
{
private Long id;
private String employeeName;
private Employer employer;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getEmployeeName()
{
return employeeName;
}
public void setEmployeeName(String employeeName)
{
this.employeeName = employeeName;
}
#ManyToOne(cascade=CascadeType.ALL, fetch = FetchType.LAZY)
public Employer getEmployer()
{
return employer;
}
public void setEmployer(Employer employer)
{
this.employer = employer;
}
}
Employer Repo
public interface EmployerServices extends JpaRepository<Employer, Long> {
}
Employee Repo
public interface EmployeeServices extends JpaRepository<Employee, Long> {
}
REST Controller is
#RestController
public class Controller {
#Autowired EmployeeServices employeeServices;
#Autowired EmployerServices employerServices;
#GetMapping("/getempr")
public Object getempr(){
return employerServices.findOne(1L);
}
}
now the problem begin start see my out put
its look like a infighting loop and my server throwing error getOutputStream() has already been called for this response.
I used #JsonBackReference & #JsonManagedReference
annotation but the problem is its working like one to many
{
"id":1,
"employerName":"employer",
"employees":[
{"id":1,"employeeName":"emp1"},
{"id":2,"employeeName":"emp2"}
]
}
if I am trying to get in the concern of many to one like all employee with employer. the output is
[
{
"id":1,
"employeeName":"emp1"
},
{
"id":2,
"employeeName":"emp2"}
]
its not showing me the employer details.
please suggets me guys what i am doing wrong. thanks in advance!!
Instead of using #JsonBackReferenceand #JsonManagedReference try to use annotation #JsonIgnoreProperties:
#JsonIgnoreProperties("employer")
private List<Employee> employees;
#JsonIgnoreProperties("employees")
private Employer employer;
It prevents Jackson from rendering a specified properties of associated objects.
with the JSON its a problem with bi-directional mapping. Use the below properties.
#JsonIgnoreProperties("employer")
#JsonIgnoreProperties("employees")
please keep fetching type as eager.
hope this will work.
You can solve your issue with two modification with annotations.
Employer.class
#Entity
public class Employer {
private Long id;
private String employerName;
#OneToMany(cascade = CascadeType.ALL,
mappedBy = "employer",
orphanRemoval = true)
private List<Employee> employees;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmployerName() {
return employerName;
}
public void setEmployerName(String employerName) {
this.employerName = employerName;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}
Employee.class
#Entity
public class Employee {
private Long id;
private String employeeName;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "employer_id")
private Employer employer;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public Employer getEmployer() {
return employer;
}
public void setEmployer(Employer employer) {
this.employer = employer;
}
}
For more information please visit this link.
Change your getEmployer Method like this:
#ManyToOne(cascade=CascadeType.ALL, fetch = FetchType.LAZY)
#JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
public Employer getEmployer()
{
return employer;
}
use
#JsonProperty(access = Access.WRITE_ONLY)
private List<Employee> employees;
So that it will ignore employees while printing to JSON in the response (and thus prevents the looping), but will still consider the JSON data (employee list) you pass in the request body so that it is available for persistence.
In JSP I have simple foreach, which should display the information from two tables. First table "Organizations" as "country" parameter keeps id of country as a foreign key to another table "Countries".
How can I show country name in this foreach, which keeps in “Organizations" as id of country?
<c:forEach items=“${organizations}" var=“organization">
<c:url var="edit" value="/edit/${organization.id}" />
<c:url var="remove" value="/remove/${organization.id}" />
<tr>
<td><c:out value="${organization.name}" /></td>
<td><c:out value="${organization.country}" /></td> // In this line
<td><c:out value="${organization.address}" /></td>
<td><c:out value="${organization.phone}" /></td>
<td><c:out value="${organization.market_cap}" /></td>
<td valign = "top">Edit</td>
<td valign = "top">Remove</td>
</tr>
</c:forEach>
Tables:
CREATE TABLE IF NOT EXISTS Organization (id int auto_increment , name varchar(255), country int, address varchar(255), phone varchar(255)primary key(id), foreign key (country) references public.country(id_country));
CREATE TABLE IF NOT EXISTS Country (id_country int auto_increment , name varchar(255), primary key(id_country));
Model, Organization:
import javax.persistence.*;
#Entity
public class Organization {
#Id
#GeneratedValue
private Integer id;
private String name;
private Integer country;
private String address;
private String phone;
private Long market_cap;
public Organization(Integer id, String name, Integer country, String address, String phone, Long market_cap) {
this.id = id;
this.name = name;
this.country = country;
this.address = address;
this.phone = phone;
this.market_cap = market_cap;
}
public Organization() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCountry() {
return country;
}
public void setCountry(Integer country) {
this.country = country;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Long getMarket_cap() {
return market_cap;
}
public void setMarketCap(Long market_cap) {
this.market_cap = market_cap;
}
}
Model, Country:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Country {
#Id
#GeneratedValue
private Integer id_country;
private String name;
private String isocode;
public Country() {
}
public Country(Integer id_country, String name, String isocode) {
this.id_country = id_country;
this.name = name;
this.isocode = isocode;
}
public Integer getId_country() {
return id_country;
}
public void setId_country(Integer id_country) {
this.id_country = id_country;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIsocode() {
return isocode;
}
public void setIsocode(String isocode) {
this.isocode = isocode;
}
}
Controller:
#Controller
#RequestMapping("/")
public class HomeController {
private final OrganizationService organizationService;
private final CountryService countryService;
#Autowired
public HomeController(final OrganizationService organizationService, final CountryService countryService) {
this.organizationService = organizationService;
this.countryService = countryService;
}
#RequestMapping(value="add", method=RequestMethod.GET)
public ModelAndView addOrganization() {
ModelAndView modelAndView = new ModelAndView("add");
Organization organization = new Organization();
modelAndView.addObject("organization", organization);
List<Country> countries = countryService.listOfCountries();
modelAndView.addObject("countries", countries);
return modelAndView;
}
#RequestMapping(value="add", method=RequestMethod.POST)
public ModelAndView addingConfirm(Organization organization)
{
ModelAndView modelAndView = new ModelAndView("confirm");
organizationService.addOrganization(organization);
String message = "Organization was successfully added.";
modelAndView.addObject("message", message);
return modelAndView;
}
#RequestMapping(method = RequestMethod.GET)
public ModelAndView list() {
ModelAndView modelAndView = new ModelAndView("index");
List<Organization> organizations = organizationService.listOfOrganizations();
modelAndView.addObject("organizations", organizations);
return modelAndView;
}
#RequestMapping(value="/edit/{id}", method=RequestMethod.GET)
public ModelAndView editOrganization(#PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView("edit");
Organization organization = organizationService.getOrganization(id);
modelAndView.addObject("organization", organization);
List<Country> countries = countryService.listOfCountries();
modelAndView.addObject("countries", countries);
return modelAndView;
}
#RequestMapping(value="/edit/{id}", method=RequestMethod.POST)
public ModelAndView editConfirm(#ModelAttribute Organization organization, #PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView("confirm");
organizationService.editOrganization(organization);
String message = "Organization was successfully edited.";
modelAndView.addObject("message", message);
return modelAndView;
}
#RequestMapping(value="/remove/{id}", method=RequestMethod.GET)
public ModelAndView removeOrganization(#PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView("confirm");
organizationService.removeOrganization(id);
String message = "Organization was successfully deleted.";
modelAndView.addObject("message", message);
return modelAndView;
}
}
Your model is inadequate for that kind operation. What you need to do is:
Your model must change:
import javax.persistence.*;
#Entity
public class Organization {
#Id
#GeneratedValue
private Integer id;
private String name;
//This will load automatically when you load your Organization entity.
#OneToOne(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
#JoinColumn(name="country")
private Country country;
private String address;
private String phone;
private Long market_cap;
public Organization(Integer id, String name, Country country, String address, String phone, Long market_cap) {
this.id = id;
this.name = name;
this.country = country;
this.address = address;
this.phone = phone;
this.market_cap = market_cap;
}
public Organization() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Long getMarket_cap() {
return market_cap;
}
public void setMarketCap(Long market_cap) {
this.market_cap = market_cap;
}
}
and in you view in that case jsp:
<c:forEach items=“${organizations}" var=“organization">
<c:url var="edit" value="/edit/${organization.id}" />
<c:url var="remove" value="/remove/${organization.id}" />
<tr>
<td><c:out value="${organization.name}" /></td>
<td><c:out value="${organization.country.name}" /></td> //Should do the trick
<td><c:out value="${organization.address}" /></td>
<td><c:out value="${organization.phone}" /></td>
<td><c:out value="${organization.market_cap}" /></td>
<td valign = "top">Edit</td>
<td valign = "top">Remove</td>
</tr>
</c:forEach>