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" />
Related
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
Among CRUD operation Create is giving error of "A different object with the same identifier value was already associated with the session" Rest all (Read, Update and Delete) is working fine.
Im using oracle sql as database and there is one more entity of product with many to one mapping with categories class.
EntityClass
#Entity
public class Categories {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
public Categories() {
super();
}
public Categories(Integer id,String name) {
this.id=id;
this.name=name;
}
public Categories(String name) {
this.name=name;
}
//with setters and getters
}
JSP page
<body onload="document.getElementById('name').disabled = true;document.getElementById('hidden').disabled = true;">
<div align="center">
<h4>Add or Modify or Delete Categories</h4>
<form:form method="POST" action="/categories" modelAttribute="categories">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td>
<form:select path="name">
<form:option value="NONE" label="Select" />
<form:options items="${categoriesList}" />
</form:select>
</td>
</tr>
<tr>
<td>Operations</td>
<td>
<input type="radio" name="Ops" value="Add" checked="checked" onclick="document.getElementById('name').disabled = true; document.getElementById('newName').disabled = false;document.getElementById('hidden').disabled = true;">Add</input><br/>
<input type="radio" name="Ops" value="Modify" onclick="document.getElementById('name').disabled = false; document.getElementById('newName').disabled = false;document.getElementById('hidden').disabled = true;">Modify</input><br/>
<input type="radio" name="Ops" value="Delete" onclick="document.getElementById('name').disabled = false; document.getElementById('newName').disabled = true;document.getElementById('hidden').disabled = false;">Delete</input><br/>
</td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="newName" id="newName"/>
<input type="hidden" id="hidden" name="newName" value="dummy"/>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</div>
</body>
Controller Class
#Controller
public class CategoriesController {
#Autowired
private CategoriesService cservice;
#RequestMapping(value = "/categories", method = RequestMethod.GET)
public ModelAndView categories() {
// view name model
ModelAndView modelAndView = new ModelAndView("categories", "categories", new Categories());
return modelAndView;
}
#RequestMapping(value = "/categories", method = RequestMethod.POST)
public String opsOnCategories(#ModelAttribute("categories") Categories cat,#RequestParam("Ops") String ops,#RequestParam("newName") String name)
{
if(ops.equals("Modify"))
{
cservice.modifyCategory(new Categories(Integer.parseInt(cat.getName()), name));
}else if(ops.equals("Add"))
{
cservice.addCategory(new Categories(name));
}else
{
cservice.deleteCategory(Integer.parseInt(cat.getName()));
}
return "categories";
}
#ModelAttribute("categoriesList")
public Map<String, String> getCategoryList() {
Map<String, String> categoriesList = new HashMap<String, String>();
List<Categories> ls=cservice.getAll();
for(int i=0;i<ls.size();i++)
{
categoriesList.put(ls.get(i).getId().toString(), ls.get(i).getName());
}
return categoriesList;
}
}
Can anyone please help on this.
Previous one due to which there was error
insert into CATEGORIES(ID,NAME) values (1,'Mobile');
insert into CATEGORIES(ID,NAME) values (2,'Laptop');
**Changes made to remove error*
insert into CATEGORIES(ID,NAME) values (hibernate_sequence.nextval,'Mobile');
insert into CATEGORIES(ID,NAME) values (hibernate_sequence.nextval,'Laptop');
My initial guess is that there something wrong with #Id #GeneratedValue with Oracle Database specifically.
There are couple of things that you can do:
1- Try to connect to any other Database type just to test the functionality - so that you can rule out what doesn't matter
2- Try to use the #org.springframework.data.annotation.Id alongside with the #Id of javax persistence
Something that look like this
#Id
#org.springframework.data.annotation.Id
private Integer id;
3- Create a class that Generates random Integer Ids and refer to it using the annotations (#GenericGenerator & #GeneratedValue)
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 working on spring-mvc application which uses Spring Security to login and hibernate as the ORM tool. So, my project only has 2 tables, Table Person has OneToMany mapping with Table Notes. So, once the user is logged into the system, he/she should be able to add notes, but while adding I would like to also save the Person's id, which is why I have used to OneToMany mapping. But I don't know how to get user's id and put it in the form. Below is my code.
The error is
org.postgresql.util.PSQLException: ERROR: null value in column "personid" violates not-null constraint
Which is understandable, thats why I want to know how I can retreive the personid.
Person model :
#Entity
#Table(name="person")
public class Person implements UserDetails{
private static final GrantedAuthority USER_AUTH = new SimpleGrantedAuthority("ROLE_USER");
#Id
#Column(name="personid")
#GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "person_seq_gen")
#SequenceGenerator(name = "person_seq_gen",sequenceName = "person_seq")
private int id;
#OneToMany(mappedBy = "person1")
private Set<Notes> notes1;
}
Note model :
#Entity
#Table(name="note")
public class Notes {
#Id
#Column(name="noteid")
#GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "note_gen")
#SequenceGenerator(name = "note_gen",sequenceName = "note_seq")
private int noteId;
#ManyToOne
#JoinColumn(name = "personid")
private Person person1;
}
SQL :
CREATE TABLE public.person (
personid INTEGER NOT NULL,
firstname VARCHAR,
username VARCHAR,
password VARCHAR,
CONSTRAINT id PRIMARY KEY (personid)
);
CREATE TABLE public.note (
noteid INTEGER NOT NULL,
sectionid INTEGER,
canvasid INTEGER,
text VARCHAR,
notecolor VARCHAR,
noteheadline VARCHAR,
personid INTEGER NOT NULL,
CONSTRAINT noteid PRIMARY KEY (noteid)
);
ALTER TABLE public.note ADD CONSTRAINT user_note_fk
FOREIGN KEY (personid)
REFERENCES public.person (personid)
ON DELETE NO ACTION
ON UPDATE NO ACTION
NOT DEFERRABLE;
Person controller :
#Controller
public class PersonController {
private PersonService personService;
#Autowired(required=true)
#Qualifier(value="personService")
public void setPersonService(PersonService ps){
this.personService = ps;
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public String listPersons(Model model) {
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
return "person";
}
//For add and update person both
#RequestMapping(value= "/person/add", method = RequestMethod.POST)
public String addPerson(#ModelAttribute("person") Person p){
//new person, add it
this.personService.addPerson(p);
return "redirect:/";
}
NoteController :
#Controller
public class NoteController {
private NotesService notesService;
#Autowired(required=true)
#Qualifier(value="notesService")
public void setNotesService(NotesService notesService){this.notesService=notesService;}
#RequestMapping(value = "/notes", method = RequestMethod.GET)
public String listNotes(Model model) {
model.addAttribute("notes", new Notes());
model.addAttribute("listnotes", this.notesService.listNotes());
return "notes";
}
#RequestMapping(value= "/note/add", method = RequestMethod.GET)
public String addNote(#ModelAttribute("notes") Notes p){
this.notesService.addNote(p);
return "redirect:/";
}
}
Note.jsp (here is where I add notes.)
<c:url var="addAction" value="/note/add" ></c:url>
<form:form action="${addAction}" commandName="notes">
<table>
<c:if test="${!empty notes.note}">
<tr>
<td>
<form:label path="noteid">
<spring:message text="noteid"/>
</form:label>
</td>
<td>
<form:input path="noteid" readonly="true" size="8" disabled="true" />
<form:hidden path="noteid" />
</td>
</tr>
</c:if>
<tr>
<td>
<form:label path="note">
<spring:message text="note"/>
</form:label>
</td>
<td>
<form:input path="note" />
</td>
</tr>
<tr>
<td>
<form:label path="notetag">
<spring:message text="notetag"/>
</form:label>
</td>
<td>
<form:input path="notetag" />
</td>
</tr>
<tr>
<td>
<form:label path="notecolor">
<spring:message text="notecolor"/>
</form:label>
</td>
<td>
<form:input path="notecolor" />
</td>
</tr>
<tr>
<td>
<form:label path="canvasid">
<spring:message text="canvasid"/>
</form:label>
</td>
<td>
<form:input path="canvasid" />
</td>
</tr>
<tr>
<td>
<form:label path="sectionid">
<spring:message text="sectionid"/>
</form:label>
</td>
<td>
<form:input path="sectionid" />
</td>
</tr>
<tr>
<td colspan="2">
<c:if test="${!empty notes.note}">
<input type="submit"
value="<spring:message text="Edit note"/>" />
</c:if>
<c:if test="${empty notes.note}">
<input type="submit"
value="<spring:message text="Add note"/>" />
</c:if>
</td>
</tr>
</table>
</form:form>
Not sure if I understood you correctly but when there is a logged in user (Principal) in a thread then you can just use SecurityContextHolder.getContext().getAuthentication().getPrincipal() to get the Principal or just inject it using #AuthenticationPrincipal or just make sure your Person implements Principal interface and inject it directly (I assume a Person is a User and a User is a Principal) to get the person.id.
In /note/add try like this:
public String addNote(#ModelAttribute("notes") Notes p, #AuthenticationPrincipal Person person)) {
p.setPerson1(person);
this.notesService.addNote(p);
return "redirect:/";
}
If you want to avoid setting it manually consider usage of AuditorAware and Auditable like here:
http://www.springbyexample.org/examples/spring-data-jpa-auditing-code-example.html
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.