Spring boot 2.5
Controller:
#org.springframework.stereotype.Controller
public class OrdersController {
#Value("${spring.application.name}")
private String appName;
#Autowired
private OrderRepository orderRepository;
#Autowired
private CategoryRepository categoryRepository;
private static Logger logger = LogManager.getLogger(OrdersController.class);
#GetMapping("/orders")
public String getAllOrders(Model model) {
model.addAttribute("ordersList", orderRepository.findAll());
model.addAttribute("appName", appName);
return "orders";
}
orders.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${appName}">Order template title</title>
<link th:href="#{/public/style.css}" rel="stylesheet"/>
<meta charset="UTF-8"/>
</head>
<body>
<div class="container entity_list">
<h2>Orders</h2>
<br/>
<table>
<tr>
<td colspan="3" align="left" th:text="'Total count: ' + ${ordersList.size()}"/>
<td colspan="3" align="right"><a th:href="#{/order/add}">Add</a></td>
</tr>
<tr>
<th width="50">ID</th>
<th width="120">Name</th>
<th width="200">Created At</th>
<th width="200">Updated At</th>
<th width="200">Category</th>
<th width="60"></th>
<th width="60"></th>
</tr>
<th:block th:each="order : ${ordersList}">
<tr>
<td th:text="${{order.id}}"/>
<td><a th:href="#{/order/view/{id}(id=${order.id})}"/><span th:text="${order.name}"/></td>
<td th:text="${{order.created}}"/>
<td th:text="${{order.updated}}"/>
<td th:text="${{order.category}}"/>
<td><a th:href="#{/order/edit/{id}(id=${order.id})}">Edit</a></td>
<td><a th:href="#{/order/delete/{id}(id=${order.id})}">Delete</a></td>
</tr>
</th:block>
</table>
</div>
</body>
</html>
jpa:
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface OrderRepository extends CrudRepository<Orders, Integer> {
// Spring Data - use JPQL -> generate SQL query on runtime
public List<Orders> findByName(String name);
public List<Orders> findByNameOrderById(String name);
}
Models:
#Entity
public class Orders {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#NotNull
private String name;
private String description;
#NotNull
#DateTimeFormat(pattern = "dd.MM.yyyy HH:mm:ss")
private Date created;
#DateTimeFormat(pattern = "dd.MM.yyyy HH:mm:ss")
private Date updated;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "category_id")
private Category category;
#Entity
public class Category {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#NotNull
private String name;
private String description;
#NotNull
#DateTimeFormat(pattern = "dd.MM.yyyy HH:mm:ss")
private Date created;
#DateTimeFormat(pattern = "dd.MM.yyyy HH:mm:ss")
private Date updated;
#OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "category")
private Orders orders;
And here result:
As you can see print category's id. But I need to print category's name.
Try to change tour orders.html and in order.category edit like below:
<td th:text="${{order.category?.name}}"/>
Hope useful
Related
creating simple match betting service. I have a problem in thymeleaf with passing the value of the match on which the user is currently betting. I want to pass the ID of the match I am betting on to the bet table. I'm not entirely sure about the entities I have whether they are designed correctly. Currently to the bet table passes me the team that the user is betting on by entering the name on input, I want to pass the match ID as well but without entering.
Bet entity
#Entity
#AllArgsConstructor
#NoArgsConstructor
#Setter
#Getter
#Builder
public class Bet {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne
#JoinColumn(name = "employee_id")
private Employee employee;
#ManyToOne(cascade = CascadeType.REMOVE)
#JoinColumn(name = "match_id")
private Match match;
#Column(name = "team_bet")
private String teamBet;
private String result;
}
Match entity
#Entity
#AllArgsConstructor
#NoArgsConstructor
#Setter
#Getter
#Builder
public class Match {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "first_team_name")
private String firstTeamName;
#Column(name = "second_team_name")
private String secondTeamName;
#DateTimeFormat(pattern ="yyyy-MM-dd")
private Date dateOut;
#OneToMany(mappedBy = "match", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Bet> bet = new HashSet<>();
private String timeOut;
}
Controllers
#GetMapping("/matches/bet/{id}")
public String createBet(Model model, #PathVariable(name = "id") int matchId) throws MatchNotFoundExceptions {
Match match = matchService.getMatch(matchId);
Bet bet = new Bet();
model.addAttribute("match", match);
model.addAttribute("bet", bet);
return "bet_form";
}
#PostMapping("/bet/save")
public String saveBet(Bet bet, RedirectAttributes redirectAttributes) {
betService.createBet(bet);
redirectAttributes.addFlashAttribute("message", "The bet has been created successfully!");
return "redirect:/bets";
}
bet_form.html
<form th:action="#{/bet/save}" method="post"
style="max-width: 700px; margin: 0 auto" th:object="${bet}">
<input type="hidden" th:field="*{id}"/>
<input type="hidden">
<form th:object="${match}">
<!--send to bet entity-->
<td th:text="${id}"></td>
</form>
<div style="text-align: center" class="m-3">
<b>Match Start: </b>
<td th:text="${#dates.format(match.dateOut, 'yyyy-MM-dd')}"></td>
<td th:text="${match.timeOut}"></td>
<div style="text-align: center" class="m-3">
<a th:text="${match.firstTeamName}"></a>
<b>VS</b>
<a th:text="${match.secondTeamName}"></a>
<div class="m-4">
<b>Team Name:</b>
<input type="text" class="form-control"
th:field="*{teamBet}" required minlength="3" maxlength="24"/>
</div>
</div>
</div>
<div class="text-center">
<div class="m-3">
<input type="submit" value="accept" class="btn btn-primary"/>
<input type="submit" value="cancel" class="btn btn-warning"
onclick="location.href='/matches';"/>
</div>
</div>
</form>
DemoModel
package com.example.demo.model;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.springframework.format.annotation.DateTimeFormat;
#Entity(name="demomodel")
public class DemoModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#NotNull
#Size(min=3, max=20)
private String fname;
private String lname;
#Min(message="Age should be 18 atleast ",value=18)
private Integer age;
#Pattern(message = "Invalid email id",regexp = "^[A-Za-z0-9+_.-]+#(.+)$")
private String email;
private String course;
#DateTimeFormat(pattern = "yyyy-MM-dd")
private Date dob;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="add_id")
private Address address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address
package com.example.demo.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#Entity
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#NotNull
#Size(min=2, max=30)
private String city;
private String state;
//#OneToOne(mappedBy="address",cascade = CascadeType.ALL)
//#JoinColumn(name="id")
#OneToOne(mappedBy="address")
private DemoModel demo;
public DemoModel getDemo() {
return demo;
}
public void setDemo(DemoModel demo) {
this.demo = demo;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
DemoController
package com.example.demo.controller;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.example.demo.model.Address;
import com.example.demo.model.DemoModel;
import com.example.demo.repository.AddressRepo;
import com.example.demo.repository.DemoRepo;
import com.example.demo.service.DemoService;
//#RestController
#Controller
public class DemoController {
private static final Logger logger = LoggerFactory.getLogger(DemoController.class);
#Autowired
DemoRepo demoRepo;
#Autowired
AddressRepo addRepo;
#Autowired
DemoService demoService;
#RequestMapping(value="/", method=RequestMethod.GET)
public String demoApp(DemoModel demoModel,Address address) {
return "home";
}
#RequestMapping(value="/formsubmit",method=RequestMethod.POST)
public String demoForm(#Valid DemoModel demoModel,BindingResult result, #Valid Address address,BindingResult res) {
if(result.hasErrors()) {
logger.warn("in first binding");
return "home";
}
else if(res.hasErrors()) {
logger.warn("in second binding");
return "home";
}
else
{
demoModel.setAddress(address);
demoRepo.save(demoModel);
//addRepo.save(address);
//mv.addObject("demoModel", demoModel);
//addRepo.save(address);
//mv.setViewName("redirect:/dashboard");
return "redirect:/dashboard";
}
}
#RequestMapping(value="/dashboard",method=RequestMethod.GET)
public String dashform(Model model){
model.addAttribute("demoModel", demoService.dashform());
return "dashboard";
}
#RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
public String delete(#PathVariable("id") int id) {
demoRepo.deleteById(id);
return "redirect:/dashboard";
}
#RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
public String edit(#PathVariable("id") int id,ModelMap modelMap,DemoModel demoModel,Address address) {
modelMap.put("demoModel", demoService.find(id));
return "edit";
}
#RequestMapping(value = "edit", method = RequestMethod.POST)
public String edit(#ModelAttribute("demoModel") DemoModel demoModel,#ModelAttribute("address") Address address,ModelMap modelMap) {
DemoModel dm=demoService.find(demoModel.getId());
dm.setFname(demoModel.getFname());
dm.setLname(demoModel.getLname());
dm.setCourse(demoModel.getCourse());
dm.setEmail(demoModel.getEmail());
dm.setAge(demoModel.getAge());
dm.setDob(demoModel.getDob());
//dm.setAddress(address);
demoRepo.save(dm);
return "edit";
}
}
DemoRepository
package com.example.demo.repository;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.model.DemoModel;
public interface DemoRepo extends CrudRepository<DemoModel, Integer> {
}
AddressRepository
package com.example.demo.repository;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.model.Address;
public interface AddressRepo extends CrudRepository<Address, Integer> {
}
DemoService
package com.example.demo.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.model.DemoModel;
import com.example.demo.repository.DemoRepo;
#Service
public class DemoService{
#Autowired
DemoRepo demoRepo;
private List<DemoModel> demoModels;
public List <DemoModel> dashform(){
demoModels=new ArrayList<DemoModel>();
for(DemoModel demoModel:demoRepo.findAll() ) {
demoModels.add(demoModel);
}
return demoModels;
}
public DemoModel find(int id) {
// TODO Auto-generated method stub
return demoRepo.findById(id).orElse(null);
}
}
edit.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><!--
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="/source/styles.css" /> -->
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Data Received</h1>
<form action="#" th:action="#{/edit}" method="post">
<div th:object="${demoModel}" >
<table th:each="demoModel: ${demoModel}">
<tr>
<td>Id:</td>
<td><input type="text" th:field="*{id}" th:placeholder="#{demoModel.id}"/></td>
<!-- <td th:if="${#fields.hasErrors('fname')}" th:errors="*{fname}">first
name Error</td> -->
</tr>
<tr>
<td>First Name:</td>
<td><input type="text" th:field="*{fname}" th:placeholder="#{demoModel.fname}"/></td>
<!-- <td th:if="${#fields.hasErrors('fname')}" th:errors="*{fname}">first
name Error</td> -->
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" th:field="*{lname}" th:placeholder="#{demoModel.lname}"/></td>
<!-- <td th:if="${#fields.hasErrors('lname')}" th:errors="*{lname}">Last
name Error</td> -->
</tr>
<tr>
<td>Email:</td>
<td><input type="text" th:field="*{email}" th:placeholder="#{demoModel.email}"/></td>
<!-- <td th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Email
Error</td> -->
</tr>
<tr>
<td>Course:</td>
<td><input type="text" th:field="*{course}" th:placeholder="#{demoModel.course}"/></td>
<!-- <td th:if="${#fields.hasErrors('course')}" th:errors="*{course}">course
Error</td> -->
</tr>
<tr>
<td>DOB:</td>
<td><input type="date" th:field="*{dob}" th:placeholder="#{demoModel.dob}"/></td>
<!-- <td th:if="${#fields.hasErrors('dob')}" th:errors="*{dob}">age
Error</td> -->
</tr>
<tr>
<td>Age:</td>
<td><input type="text" th:field="*{age}" th:placeholder="#{demoModel.age}"/></td>
<!-- <td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">age
Error</td> -->
</tr>
</table>
</div>
<div th:object="${address}">
<table th:each="demoModel: ${demoModel}">
<tr>
<td>State:</td>
<td><input type="text" th:field="*{state}" th:placeholder="#{demoModel.address.state}"/></td>
</tr>
<tr>
<td>City:</td>
<td><input type="text" th:field="*{city}" th:placeholder="#{demoModel.address.city}"/></td>
</tr>
</table>
</div>
<button type="submit">Submit</button>
</form>
</body>
</html>
dashboard.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<link rel="stylesheet" href="/source/styles.css" /><!--
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet"> -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"><!--
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> -->
</head>
<body>
<h1>Data Received</h1>
<table>
<tr >
<th rowspan=2>Id</th>
<th rowspan=2>First Name</th>
<th rowspan=2>Last Name</th>
<th rowspan=2>Email</th>
<th rowspan=2>Age</th>
<th rowspan=2>Date of Birth</th>
<th rowspan=2>Course</th>
<th colspan=2>Address</th>
<th rowspan=2>Action</th>
</tr>
<tr>
<th>City</th>
<th>State</th>
</tr>
<tr th:each="demoModel: ${demoModel}">
<td th:text="${demoModel.id}">Id</td>
<td th:text="${demoModel.fname}">First Name</td>
<td th:text="${demoModel.lname}">Last Name</td>
<td th:text="${demoModel.email}">Email</td>
<td th:text="${demoModel.age}">Age</td>
<td th:text="${demoModel.dob}">DOB</td>
<td th:text="${demoModel.course}">Course</td>
<td th:text="${demoModel.address.city}">City</td>
<td th:text="${demoModel.address.state}">State</td>
<td> <a class="btn" th:href="#{/delete/{id}/(id=${demoModel.id})}"> <span class="glyphicon glyphicon-trash"></span> </a>
<a class="btn" th:href="#{/edit/{id}/(id=${demoModel.id})}"> <span class="glyphicon glyphicon-edit"></span> </a>
</td>
</tr>
</table>
<h2> Go to form </h2>
</body>
Dashboard
Edit
So, the question is how to update two tables? When I click on edit then it is redirected to the edit page where I see the details of demoModel object but the details of address object is not displayed. I don't know whether this issue prevent me to update both the tables or there is another problem in controller for updating data.
While I access the edit page without the intention of updating the details of both the tables demoModel and address is being fetched efficiently for a particular ID.
My Intention of Updating both the table is failed here.
Please, experts go through all the codes above and suggest me a better solution how can I update both the OneToOne mapped table.
You don't see address because it's not loaded.
modelMap.put("demoModel", demoService.find(id));
Here you are passing only DemoModel and you need also to load Address. In Your DemoModel should define
#OneToOne(mappedBy="address", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumn(name="add_id")
private Address address;
Now also in your edit Address object should be present
I am trying to send some value in my jsp to a portlet class.I am using jstl to achieve that ,my requirement is to use requestScope to pass the value in the portlet.Here i have seen that when i am using requestScope to create URL in portlet it is working fine,but in case of value passing it is not working,i am posting my code what i have done so far
<fmt:setBundle basename="Language-ext"/>
<form action="<c:out value='${requestScope.registerUserActionUrl}'/>" method="POST">
<table width="200px">
<tr>
<td colspan="2">
<font color="#FF0000"><c:out
value="${requestScope.errorMsg}"/></font>
</td>
</tr>
<tr>
<td><fmt:message key="label.firstName"/></td>
<td><input type="text" name="firstName" value="${requestScope.User.firstName}"></input></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><fmt:message key="label.lastName"/></td>
<td><input type="text" name="lastName" value="${requestScope.User.lastName}"></input></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><font color="#FF0000"><b>*</b></font> <fmt:message key="label.email"/></td>
<td><input type="text" name="email" value="${requestScope.User.email}"></input> </td>
</tr>
<tr>
<td> </td>
</tr>
<tr align="center">
<td colspan="2">
<input type="submit"/>
<a href="<c:out value='${requestScope.resetRenderUrl}'/>">
<b><fmt:message key="label.reset"/></b>
</a>
</td>
</tr>
And this is my bean class
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = -5729328658617182010L;
private String firstName;
private String lastName;
private String email;
public User(String firstName,String lastName,String email){
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
And this is the portlet where i am catching the value
#ProcessAction(name = "registerUserAction")
public void registerUser(ActionRequest request, ActionResponse response)
throws PortletException, IOException {
String email = request.getParameter("email");
System.out.println("Email :"+email +","+request.getParameter("firstName"));
// --set the information entered by the user on the registration
But i am getting null for both email and firstName .Somebody please help
Answer relevant for Liferay 6.2
By default, Liferay 6.2 requires request parameters for a given portlet to be prefixed with the portlet namespace. In plain HTML, you need to specify the namespace for each request parameter / form field explicitely by using <portlet:namespace/> tag:
<input type="text" name="<portlet:namespace/>firstName" value="${requestScope.User.firstName}">
Don't forget the required TLD import:
<%#taglib prefix="portlet" uri="http://java.sun.com/portlet" %>
Only the namespaced parameters are visible to the portlet (through standard portlet API).
I am developing a small Spring and hibernate base application in java, and my appication has a one to many relationship with Employee and Unit, Employee has a one unit, Unit has a many Employee.
in this small application genarate error like this `
I was hard code data to Unit schema table, i populate unit combobox filled in jsp its works, but inside the #controller unit has a null data.
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Column 'unit_id' cannot be null
if allow to null value to unit_id other data inserted with out insert unit_id
here my Entity class
#Entity
#Table(name = "employee")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "epf")
private int epf;
#Column(name = "fname")
private String fname;
#Column(name = "lname")
private String lname;
#Column(name = "email")
private String email;
#JoinColumn(name = "unit_id", referencedColumnName = "id")
#ManyToOne//(optional = false)
private Unit unit;
#Entity
#Table(name = "unit")
public class Unit implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "name")
My controller Class
#Autowired
private EmployeeService employeeService;
private DesignationService designationService;
#RequestMapping({"/index", "/"})
public String setupForm(Map<String, Object> map){
Employee student = new Employee();
map.put("employee", student);
map.put("employeeList", employeeService.getAllEmployee());
map.put("unitList", employeeService.getAllUnitList());
return "employee";
}
#RequestMapping(value="/employee.do", method=RequestMethod.POST)
public ModelAndView doActions(#ModelAttribute Employee emp, BindingResult result, #RequestParam String action, Map<String, Object> map){
ModelAndView modelAndView = new ModelAndView("employee");
Employee employeetResult = new Employee();
switch(action.toLowerCase()){ //only in Java7 can put String in switch
case "add":
employeeService.addEmployee(emp);
employeetResult = emp;
break;
case "edit":
employeeService.updateEmployee(emp);
employeetResult = emp;
break;
case "delete":
employeeService.deleteEmployee(emp.getId());
employeetResult = new Employee();
break;
case "search":
Employee searchedStudent = employeeService.getEmployee(emp.getId());
employeetResult = searchedStudent!=null ? searchedStudent : new Employee();
break;
}
map.put("employee", employeetResult);
map.put("employeeList", employeeService.getAllEmployee());
return modelAndView;
}
My JSP
<form:form action="employee.do" method="POST" commandName="employee">
<table width="341" border="0">
<tr>
<td width="154"> </td>
<td width="21"> </td>
<td width="152"> </td>
</tr>
<tr>
<td><spring:message code="employee.id"/></td>
<td> </td>
<td><form:input path="epf" /></td>
</tr>
<tr>
<td><spring:message code="employee.epf"/></td>
<td> </td>
<td><form:input path="epf" /></td>
</tr>
<tr>
<td><spring:message code="employee.fname"/></td>
<td> </td>
<td><form:input path="fname"/></td>
</tr>
<tr>
<td><spring:message code="employee.lname"/></td>
<td> </td>
<td><form:input path="lname" /></td>
</tr>
<tr>
<td><spring:message code="employee.email"/></td>
<td> </td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td><spring:message code="employee.unit"/></td>
<td> </td>
<!-- Unit Combo filling --><td>
<form:select path="unit" multiple="false" size="1">
<form:options items="${unitList}" itemValue="id" itemLabel="name"/>
</form:select>
<!-- Unit Combo filling end --></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="action" value="Add" />
<input type="submit" name="action" value="Edit" />
<input type="submit" name="action" value="Delete" />
<input type="submit" name="action" value="Search" />
</td>
</tr>
</table>
</form:form>
My DAO Class
> #Repository public class EmployeeDaoImp implements EmployeeDao {
>
> #Autowired private SessionFactory sessionfactory;
> public void addEmployee(Employee emp) { sessionfactory.getCurrentSession().save(emp);
>
> }
>
> public void updateEmployee(Employee emp) {
> sessionfactory.getCurrentSession().update(emp);
>
> }
>
> public void deleteEmployee(int id) {
> sessionfactory.getCurrentSession().delete(getEmployee(id)); }
>
> Employee public Employee getEmployee(int empId) {
> return (Employee) sessionfactory.getCurrentSession().get(Employee.class,empId); }
>
> public List getAllEmployee() {
> return sessionfactory.getCurrentSession().createQuery("from Employee").list(); }
The id is primary key in the DB. You are save an object without giving it's value. So either make it auto increment in table or generate it's value using hibernate.
On my page I would like to get only one user details. The problem being that I'm having problems with displaying the details of the user on the page. The object that I'm trying to retrieve has a onetomany relationship with another class. So I would like to list the associated objects as well.
Model
#Entity
#Table(name = "user")
#Component
public class UserEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "user_id")
private Integer userId;
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="setter")
private Set<Module> sModule = new HashSet<Module>();
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="checker")
private Set<Module> cModule = new HashSet<Module>();
Controller
#RequestMapping(value = "/main/user/testing", method = RequestMethod.GET)
public String getRecords(#RequestParam("userId") Integer userId, ModelMap
model) {
if(userId !=null)
{
UserEntity user = userService.getUserByID(userId);
model.addAttribute("user", user);
}
return "/main/user/testing";
}
Jsp page
<table>
<tr>
<th>User Id</th>
<th>Name</th>
<th>Module Code</th>
<th>Module Name</th>
</tr>
<c:forEach items="${user}" var="obj" >
<c:forEach items="${obj.sModule}" var="module" >
<tr>
<td><c:out value="${obj.userId}" escapeXml="true" /></td>
<td><c:out value="${obj.name}" escapeXml="true" /></td>
<td><c:out value="${module.moduleCode}" escapeXml="true" /></td>
<td><c:out value="${module.moduleName}" escapeXml="true" /></td>
</tr>
</c:forEach>
</c:forEach>
</table>
Using the controller code, when I try to access the page. The user details are not included. So I wanted to know if there was a way I would be able to render the object for just one user instead of a list of users.
Why do you use <c:forEach items="${user}" var="obj" >? It looks that UserEntity is an object but not List. So, remove <c:forEach items="${user}" var="obj" > and try
<c:out value="${user.userId}" escapeXml="true" />