How can I update object from database without inserting new? - spring-boot

i want to update object from my database without inserting new to the DB.
here are 2 methods:
#RequestMapping("/edit/{id}")
public ModelAndView showEditProductPage(#PathVariable(name = "id") Integer id, Model model) {
ModelAndView modelAndView = new ModelAndView("edit_customer");
Customer customer = customerService.getCustomer(id);
//Customer customer = customerRepository.getOne(id);
//customer.setCustomerId(customerRepository.getOne(id).getCustomerId());
System.out.println(customer.getCustomerId());
System.out.println(customer.toString());
model.addAttribute("customer", customer);
modelAndView.addObject("customer", customer);
return modelAndView;
}
output is: id=1 Customer{id=1, firstName='Krzysztof', address='ulica 1', phoneNumber='123456789'}
#RequestMapping("/update/{id}")
public String updateCustomer(#PathVariable(name = "id") Integer id,
#ModelAttribute("customer") Customer customer){
//System.out.println(id);
//customer.setCustomerId(id);
System.out.println("____________________");
System.out.println("customer id " + customer.getCustomerId());
System.out.println("____________________");
customer.setCustomerId(id);
System.out.println("customer id " + customer.getCustomerId());
System.out.println("owner " + customer.getOwner());
System.out.println("address " + customer.getAddress());
System.out.println("phone number " + customer.getAddress());
System.out.println("to string: " + customer.toString());
System.out.println("id " + id);
customerService.save(customer);
return "redirect:/";
}
output after second method is: id=1 Customer{id=null, firstName='Krzysztof', address='ulica 1zzz', phoneNumber='123456789'}
customer repository extends JPA repository,
save method:
public void save(Customer customer) {
customerRepository.save(customer);
}
thymeleaf template:
!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<title>Edit Customer</title>
<link rel="stylesheet" type="text/css" th:href="#{/table.css}" />
</head>
<body>
<div align="center">
<h1>Edit Customer</h1>
Go Back
<br />
<form action="#" th:action="#{'/update/' + ${id}}" th:object="${customer}"
method="post">
<table border="0" cellpadding="10">
<tr>
<td>Customer ID:</td>
<td>
<input type="text" th:field="*{customerId}" readonly="readonly" />
</td>
</tr>
<tr>
<td>First Name:</td>
<td>
<input type="text" th:field="*{owner}" />
</td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" th:field="*{address}" /></td>
</tr>
<tr>
<td>Phone Number:</td>
<td><input type="text" th:field="*{phoneNumber}" /></td>
</tr>
<tr>
<td colspan="2"><button type="submit">Save</button> </td>
</tr>
</table>
</form>
</div>
</body>
</html>
customer entity class:
package com.praca.manager.entity;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "customer")
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer customerId;
#Column(name = "owner")
private String owner;
#Column(name = "address")
private String address;
#Column(name = "phone_number")
private String phoneNumber;
#OneToMany(mappedBy = "customer")
List<Details> details;
public Customer(){
}
public Customer(Integer customerId,
String owner,
String address,
String phoneNumber){
this.customerId = customerId;
this.owner = owner;
this.address = address;
this.phoneNumber = phoneNumber;
}
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer id){
this.customerId = customerId;
}
public String getOwner() {
return owner;
}
public void setOwner(String firstName) {
this.owner = firstName;
}
public String getAddress() {
return address;
}
public void setAddress(String address){
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
#Override
public String toString() {
return "Customer{" +
"id=" + customerId +
", firstName='" + owner + '\'' +
", address='" + address + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
'}';
}
}
here ID field is also '1'
sql script:
create table customer(
customer_id int auto_increment primary key not null,
owner varchar(200) not null,
address varchar(200) not null,
phone_number int not null
);
despite i try to set id to 1 or any other number, it is still null.
Can anyone tell me why and how to fix it?

The issue is in the setter of your Customer class:
public void setCustomerId(Integer id){
this.customerId = customerId;
}
You assigned the field to itself, that's why it's always null. Should be "this.customerId = id" :).

Related

How to create java spring-mvc form with hibernate #OneToOne,#ManyToOne... annotations with #ModelAttribute

I want to create a controller with #ModelAttribute which allows me to insert to my Customer table data. I've done one with the employee but how can I save two hibernate mapped entities in JSP form with #ModelAttribute? also, I'm using basic generated repositories with JpaRepository interface. I want to make those two entities in relation saving it.
I tried to make #ModelAttribute JSP forms, but I don't know how to set other table entity in relation.
Employee
#Entity
#Table
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
#Digits(integer = 10, fraction = 0, message = "Must be a digit")
private Integer age;
private BigDecimal salary;
#Temporal(TemporalType.DATE)
#DateTimeFormat(pattern = "yyyy-MM-dd")
#PastOrPresent(message = "Date must be past or present")
private Date birthDate;
#Temporal(TemporalType.DATE)
#DateTimeFormat(pattern = "yyyy-MM-dd")
#PastOrPresent(message = "Date must be past or present")
private Date hireDate;
private boolean sex; //false - woman, true - man
#OneToOne(mappedBy = "employee")
private Address address;
public Employee() {
}
public Employee(String firstName, String lastName, Integer age, BigDecimal salary, Date birthDate, Date hireDate,
boolean sex) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.salary = salary;
this.birthDate = birthDate;
this.hireDate = hireDate;
this.sex = sex;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public Date getHireDate() {
return hireDate;
}
public void setHireDate(Date hireDate) {
this.hireDate = hireDate;
}
public boolean isSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address
#Entity
#Table
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String country;
private String city;
private String street;
private Integer houseNumber;
private Integer local;
private String postalCode;
#OneToOne
#JoinColumn(name = "employee_id")
private Employee employee;
public Address() {
}
public Address(String country, String city, String street, Integer houseNumber, Integer local, String postalCode) {
this.country = country;
this.city = city;
this.street = street;
this.houseNumber = houseNumber;
this.local = local;
this.postalCode = postalCode;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public Integer getHouseNumber() {
return houseNumber;
}
public void setHouseNumber(Integer houseNumber) {
this.houseNumber = houseNumber;
}
public Integer getLocal() {
return local;
}
public void setLocal(Integer local) {
this.local = local;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
Controller
#Controller
#RequestMapping("/user")
public class UserController {
#Autowired
public EmployeeService employeeService;
#Autowired
public AddressService addressService;
#GetMapping("/add")
public String addUser(Model model) {
model.addAttribute("employee", new Employee());
return "user/addEmployee";
}
#PostMapping("/add")
public String postAddUser(#Valid #ModelAttribute("employee") Employee employee, BindingResult bs) {
if(bs.hasErrors()) {
return "user/addAddress";
} else {
employeeService.saveOrUpdate(employee);
return "user/success";
}
}
#GetMapping("/address/add")
public String addAddress(Model model) {
List<Employee> employees = employeeService.findAll();
model.addAttribute("employees", employees);
model.addAttribute("address", new Address());
return "user/addAddress";
}
#PostMapping("/address/add")
public String postAddAddress(#ModelAttribute("address") Address address, #RequestParam("employee_id") Long id) {
Employee employee = employeeService.findById(id);
address.setEmployee(employee);
employee.setAddress(address);
addressService.saveOrUpdate(address);
employeeService.saveOrUpdate(employee);
return "user/addAddress";
}
}
addAddress.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head></head>
<body>
<h2>Address Form</h2>
<form:form action="/user/address/add" method="POST" modelAttribute="address">
City: <form:input path="city"/><br>
Street: <form:input path="street" /><br>
House Number: <form:input path="houseNumber"/><br>
Local: <form:input path="local"/><br>
Postal Code: <form:input path="postalCode" /><br>
<select name="employee_id">
<c:forEach var="employee" items="${employees}">
<option value="${employee.id}">${employee.id} ${employee.firstName} ${employee.lastName}</option>
</c:forEach>
</select><br>
<input type="submit" />
</form:form>
</body>
</html>
addEmployee.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head></head>
<body>
<h2>Employee Form</h2>
<form:form action="/user/add" method="POST" modelAttribute="employee">
First Name: <form:input path="firstName"/> <form:errors path="firstName"></form:errors><br>
Last Name: <form:input path="lastName"/> <form:errors path="lastName"></form:errors><br>
Age: <form:input path="age" /> <form:errors path="age" type="number"></form:errors><br>
Salary: <form:input path="salary" type="number"/> <form:errors path="salary"></form:errors><br>
Birth Date<form:input path="birthDate" type="date"/> <form:errors path="birthDate"></form:errors><br>
Hire Date<form:input path="hireDate" type="date" /> <form:errors path="hireDate"></form:errors><br>
Female: <form:radiobutton path="sex" value="0" /> Male: <form:radiobutton path="sex" value="1" /><br>
<input type="submit" value="Wyślij"/>
</form:form>
</body>
</html>
I need to create a result in the database with those two entities with a relationship using #ModelAttribute. Is it possible?
If I understood your problem correctly,
To set the associated entity -
you need to have unique value to identify the entity (for ex. Employeeid for employees),
fetch the details for the Employeeid, this will result in employee entity object
set the employee entity object into customer entity object
similarly for Invoices.
then save customer entity object.
Check - https://thoughts-on-java.org/ultimate-guide-association-mappings-jpa-hibernate/
You could try to combine them something like this:
<form:form action="add" method="POST" modelAttribute="employee">
<form:hidden path="id"/>
First Name: <form:input path="firstName"/> <form:errors path="firstName"></form:errors><br>
Last Name: <form:input path="lastName"/> <form:errors path="lastName"></form:errors><br>
Age: <form:input path="age" /> <form:errors path="age" type="number"></form:errors><br>
Salary: <form:input path="salary" type="number"/> <form:errors path="salary"></form:errors><br>
Birth Date<form:input path="birthDate" type="date"/> <form:errors path="birthDate"></form:errors><br>
Hire Date<form:input path="hireDate" type="date" /> <form:errors path="hireDate"></form:errors><br>
Female: <form:radiobutton path="sex" value="0" /> Male: <form:radiobutton path="sex" value="1" /><br>
<form:form action="add" method="POST" modelAttribute="address">
<form:hidden path="addressId"/> // <- need to rename in your entity Address class
City: <form:input path="city"/><br>
Street: <form:input path="street" /><br>
House Number: <form:input path="houseNumber"/><br>
Local: <form:input path="local"/><br>
Postal Code: <form:input path="postalCode" /><br>
<select name="employee_id">
<c:forEach var="employee" items="${employees}">
<option value="${employee.id}">${employee.id} ${employee.firstName} ${employee.lastName}</option>
</c:forEach>
</select><br>
<input type="submit" value="Submit"/>
</form:form>
<input type="submit" />
</form:form>
In controller method:
#PostMapping("/add")
public String postAdd(#ModelAttribute("employee") #Valid Employee employee
BindingResult empBindingResult,
#ModelAttribute("address") Address address,
BindingResult addressBindingResult) {
// other code
}
Although I didn't use radiobutton and selector elements in this combination, the rest of code should work fine.
Spring MVC Multiple ModelAttribute On the Same Form
Multiple modelattributes in a JSP with Spring

How to insert into two tables from jsp by using spring mvc and hibernate

I want to insert into two tables from jsp using spring mvc4 and hibernate.
Here is my two model class.
1)Employee.java
package com.websystique.springmvc.model;
import java.math.BigDecimal;
import javax.persistence.CascadeType;
import javax.persistence.Column;
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.persistence.Table;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.Type;
import org.hibernate.validator.constraints.NotEmpty;
import org.joda.time.LocalDate;
import org.springframework.format.annotation.DateTimeFormat;
import com.websystique.springmvc.model.UserLogin;;
#Entity
#Table(name="EMPLOYEE")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Size(min=3, max=50)
#Column(name = "NAME", nullable = false)
private String name;
#NotNull
#DateTimeFormat(pattern="dd/MM/yyyy")
#Column(name = "JOINING_DATE", nullable = false)
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
private LocalDate joiningDate;
#NotNull
#Column(name = "SALARY", nullable = false)
private int salary;
#NotEmpty
#Column(name = "SSN", unique=true, nullable = false)
private String ssn;
#Column(name="emp_id",nullable=true)
private String emp_id;
public UserLogin getUserlogin() {
return userlogin;
}
public void setUserlogin(UserLogin userlogin) {
this.userlogin = userlogin;
}
public String getEmp_id() {
return emp_id;
}
public void setEmp_id(String emp_id) {
this.emp_id = emp_id;
}
#OneToOne(targetEntity=UserLogin.class,cascade=CascadeType.ALL)
#JoinColumn(name="emp_id",referencedColumnName="emp_id",insertable=false, updatable=false)
private UserLogin userlogin;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getJoiningDate() {
return joiningDate;
}
public void setJoiningDate(LocalDate joiningDate) {
this.joiningDate = joiningDate;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((ssn == null) ? 0 : ssn.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Employee))
return false;
Employee other = (Employee) obj;
if (id != other.id)
return false;
if (ssn == null) {
if (other.ssn != null)
return false;
} else if (!ssn.equals(other.ssn))
return false;
return true;
}
#Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", joiningDate="
+ joiningDate + ", salary=" + salary + ", ssn=" + ssn + "]";
}
}
2)UserLogin.java
package com.websystique.springmvc.model;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
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.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
#Entity
#Table(name="users")
public class UserLogin implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name="emp_id", unique=true, nullable=true)
private String emp_id;
#Column(name="user_name",nullable=false)
private String user_name;
#Column(name="password",nullable=false)
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
And here is my jsp page(registration.jsp)
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee Registration Form</title>
<style>
.error {
color: #ff0000;
}
</style>
</head>
<body>
<h2>Registration Form</h2>
<form:form method="POST" modelAttribute="employee">
<form:input type="hidden" path="id" id="id"/>
<table>
<tr>
<td><label for="name">Name: </label> </td>
<td><form:input path="name" id="name"/></td>
<td><form:errors path="name" cssClass="error"/></td>
</tr>
<tr>
<td><label for="user_name">User Name: </label> </td>
<td><form:input path="user_name" id="user_name"/></td>
<td><form:errors path="user_name" cssClass="error"/></td>
</tr>
<tr>
<td><label for="pwd">Password: </label> </td>
<td><form:input type="password" path="password" id="password"/></td>
<td><form:errors path="password" cssClass="error"/></td>
</tr>
<tr>
<td><label for="joiningDate">Joining Date: </label> </td>
<td><form:input path="joiningDate" id="joiningDate"/></td>
<td><form:errors path="joiningDate" cssClass="error"/></td>
</tr>
<tr>
<td><label for="salary">Salary: </label> </td>
<td><form:input path="salary" id="salary"/></td>
<td><form:errors path="salary" cssClass="error"/></td>
</tr>
<tr>
<td><label for="ssn">SSN: </label> </td>
<td><form:input path="ssn" id="ssn"/></td>
<td><form:errors path="ssn" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3">
<c:choose>
<c:when test="${edit}">
<input type="submit" value="Update"/>
</c:when>
<c:otherwise>
<input type="submit" value="Register"/>
</c:otherwise>
</c:choose>
</td>
</tr>
</table>
</form:form>
<br/>
<br/>
Go back to List of All Employees
</body>
</html>
Here is my controller
#RequestMapping(value = { "/new" }, method = RequestMethod.POST)
public String saveEmployee(#Valid Employee employee,#Valid UserLogin userLogin, BindingResult result,
ModelMap model) {
System.out.println("inside controller");
System.out.println("result>>>> "+result);
if (result.hasErrors()) {
System.out.println("inside controller1111111111");
return "registration";
}
if(!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())){
System.out.println("inside controller1111111111222222222222222222222");
FieldError ssnError =new FieldError("employee","ssn",messageSource.getMessage("non.unique.ssn", new String[]{employee.getSsn()}, Locale.getDefault()));
result.addError(ssnError);
return "registration";
}
String emp="Emp-"+employee.getId()+"-"+employee.getName();
System.out.println("emp>>> "+emp);
employee.setEmp_id(emp);
service.saveEmployee(employee);
userservice.saveUser(userLogin);
model.addAttribute("success", "Employee " + employee.getName() + " registered successfully");
return "success";
}
So I want to save user_name and password into login table and rest of the data want to save into another table. Is there anyone who can help me how to insert data into two tables. I searched a lot but did not get fruitful result. Any link for this problem is also appreciated. Thanks in advance
You can use entity inheritance. Check this http://www.thoughts-on-java.org/complete-guide-inheritance-strategies-jpa-hibernate/
. Select strategy which fits your reqirements.

Error with NullPointerExcetion Native Method Accessor, Can give me a solution

i browse "http://localhost:8080/subject/form" for fill information in Subjectform.jsp, after will direct "http://localhost:8080/subject/add" for insert subject object in table subject. But it not insert subject object and encouter following error:
null<br/>
edu.java.spring.controller.SubjectController.addSubject(SubjectController.java:5
0)<br/>
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)<br/>
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)<br
/>
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.jav
a:43)<br/>
java.lang.reflect.Method.invoke(Method.java:497)<br/>
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHa
ndlerMethod.java:215)<br/>
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(I
nvocableHandlerMethod.java:132)<br/>
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMet
hod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)<br/>
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapt
er.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)<br/>
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapt
er.handleInternal(RequestMappingHandlerAdapter.java:689)<br/>
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(A
bstractHandlerMethodAdapter.java:83)<br/>
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.j
ava:938)<br/>
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.ja
va:870)<br/>
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet
.java:961)<br/>
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:86
3)<br/>
javax.servlet.http.HttpServlet.service(HttpServlet.java:707)<br/>
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:8
37)<br/>
javax.servlet.http.HttpServlet.service(HttpServlet.java:790)<br/>
org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:801)<br/>
org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:587)<br/>
org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)<br
/>
org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)<br/>
org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223
)<br/>
org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:112
6)<br/>
org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)<br/>
org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
<br/>
org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1060
)<br/>
org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)<br
/>
org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerC
ollection.java:215)<br/>
org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java
:110)<br/>
org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:113)<
br/>
org.eclipse.jetty.server.Server.handle(Server.java:509)<br/>
org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:288)<br/>
org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:240)<br/>
org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:539)<br/>
org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:620)
<br/>
org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:540)<
br/>
java.lang.Thread.run(Thread.java:745)<br/>
Here file SubjectController.class
#Controller
public class SubjectController {
#Autowired
public StudentDAO studentDao;
public SubjectDao subjectDao;
#RequestMapping(value = "subject/form",method = RequestMethod.GET)
public ModelAndView subjectForm (){
ModelAndView model = new ModelAndView("SubjectForm", "subject", new Subject());
List<Student> students = studentDao.listStudents();
Map<Integer,String> map = new HashMap<Integer,String>();
for(int i=0;i<students.size();i++){
map.put(students.get(i).getId(), students.get(i).getName());
}
model.getModelMap().put("studentList",map);
return model;
}
#RequestMapping(value="subject/add",method = RequestMethod.POST)
public void addSubject(#Valid #ModelAttribute("subject")Subject subject){
// ModelAndView model = new ModelAndView("redirect:/subject/list");
subjectDao.insert(subject);
// return model;
}
Here file SubjectHibernateDaoImpl.class
public class SubjectHibernateDaoImpl implements SubjectDao {
#Autowired
public LocalSessionFactoryBean sessionFactory;
#Override
public void insert(Subject subject){
Session session = sessionFactory.getObject().openSession();
try {
session.save(subject);
session.flush();
} finally {
// TODO: handle finally clause
session.close();
}
}
public List<Subject> listSubject() {
// TODO Auto-generated method stub
Session session = sessionFactory.getObject().openSession();
Query query = session.createQuery("from Subject");
try {
return query.list();
} finally {
// TODO: handle finally clause
session.close();
}
}
Here file Subject.class
#Entity
#Table(name = "subject",uniqueConstraints={#UniqueConstraint(columnNames="id")})
public class Subject {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "title", nullable = false, length = 200)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name = "student", nullable = false)
public int getStudent() {
return student;
}
public void setStudent(int student) {
this.student = student;
}
#Column(name = "score", nullable = false)
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int id;
public String title;
public int student;
public int score;
}
Here file Subject.jsp
<html>
<head>
<title>Add New Subject Information</title>
</head>
<body>
<h2>Please Input Subject Information</h2>
<form:form method="POST" modelAttribute="subject" action="add">
<table>
<tr>
<td><form:label path="student">Student</form:label></td>
<td><form:input path="student" type = "number"/></td>
</tr>
<tr>
<td><form:label path="title">Title</form:label></td>
<td><form:input path="title"/></td>
</tr>
<tr>
<td><form:label path="score">Score</form:label></td>
<td><form:input path="score" type = "number"/></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Submit"/></td>
</table>
</form:form>
</body>
</html>
Looks like you forgot to add the #Autowired annotation. It's present for the studentDao but not for the subjectDao, resulting in that object not being initialized.

Spring and Hibernate form binding

Ok I am having an issue and have been stuck for a few hours. I am running the current version of spring with Hibernate and need to take data from a form and save it do the database, that's all but it is giving me tons of trouble and have no idea how to go about it. Below is the controller, JSP, Model, and Dao.
Controller
private final String addNewView = "addAward";
#RequestMapping(value = "/addAwardType", method = RequestMethod.GET)
public String addAwardType() {
LOG.debug("Display form to add a new contact.");
return addNewView;
}
#RequestMapping(value = "/addAwardType", method = RequestMethod.POST)
public ModelAndView addAwardType(
#ModelAttribute("AwardTypeModel") AwardType awardType,
BindingResult result) {
return new ModelAndView(addNewView, "AwardType", new AwardTypeModel(awardType));
}
}
JSP
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Add AwardType</h2>
<form:form method="POST" commandName="addAwardType">
<table>
<tr>
<td><form:label path="AwardType.name">Award Name</form:label></td>
<td><form:input path="AwardType.name" /></td>
</tr>
<tr>
<td><form:label path="AwardType.description">Last Name</form:label></td>
<td><form:input path="AwardType.description" /></td>
</tr>
<tr>
<td> <form:checkbox path="AwardType.isActive" value="Active"/></td>
</tr>
<tr>
<td><form:label path="AwardType.created"></form:label></td>
<td><form:input path="AwardType.created" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Award"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
Model
public class AwardTypeModel extends BaseModel {
private int id;
private String name;
private String description;
private boolean active;
private Date created;
private Date modified;
/**
* Construct from persistence object
* A similar constructor will be needed in each model
* #param dbo - the Persistence Object (data base object)
*/
public AwardTypeModel(AwardType dbo){
this.id = dbo.getAwardTypeId();
this.name = dbo.getAwardName();
this.description = dbo.getDescription();
this.active = dbo.isActive();
this.created = dbo.getCreated();
this.modified = dbo.getModified();
}
/* (non-Javadoc)
* #see com.eaglecrk.recognition.model.BaseModel#convertToDb()
*/
#Override
public BasePersistence convertToDb() {
AwardType dbo = new AwardType();
dbo.setAwardTypeId(this.id);
dbo.setAwardName(this.name);
dbo.setDescription(this.description);
dbo.setActive(this.active);
dbo.setCreated(this.created);
dbo.setModified(this.modified);
return dbo;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
}

Spring Validator for duplicate record in database

In my page jsp, i have a form where i can add a user to my database, and i use a validator to show errors when fields are empty, but what i want to do is, when i insert a duplicate entry of the primary key of my table, the validator show me a message that this login for example is already taken instead having an error by Apache!
this is my User POJO :
package gestion.delegation.domaine;
import java.io.Serializable;
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
int id;
String nom;
String prenom;
String login;
String password;
String role;
boolean enable;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean getEnable() {
return this.enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public User(int id, String nom, String prenom, String login,
String password, String role, boolean enable) {
super();
this.id = id;
this.nom = nom;
this.prenom = prenom;
this.login = login;
this.password = password;
this.role = role;
this.enable = enable;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public User() {
super();
}
}
and this is my validator :
package gestion.delegation.validator;
import gestion.delegation.domaine.User;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class AddUserValidator implements Validator{
#Override
public boolean supports(Class<?> clazz) {
return User.class.isAssignableFrom(clazz);
}
#Override
public void validate(Object obj, Errors err) {
ValidationUtils.rejectIfEmptyOrWhitespace(err, "nom", "name.required","Choisissez un nom");
ValidationUtils.rejectIfEmptyOrWhitespace(err, "prenom", "prenom.required", "Choisissez un prenom");
ValidationUtils.rejectIfEmptyOrWhitespace(err, "login", "login.required", "Choisissez un login");
ValidationUtils.rejectIfEmptyOrWhitespace(err, "password", "password.required", "Choisissez un password");
ValidationUtils.rejectIfEmpty(err, "role", "role.required", "Choisissez un role");
}
}
the form :
<c:if test="${not empty msg_success}">
<div class="success">Vous avez ajouter un utilisateur avec
succès !</div>
</c:if>
<form:form name="ajf"
action="${pageContext.request.contextPath}/ajouter_user"
method="post" commandName="user">
<table id="tabmenu">
<tr>
<td id="idtab">Nom :</td>
<td><form:input type="text" path="nom"
class="round default-width-input" name="name_" /></td>
<td><form:errors path="nom" Class="errorbox" /></td>
</tr>
<tr>
<td id="idtab">Prénom :</td>
<td><form:input type="text" path="prenom" name="prenom_"
class="round default-width-input" /></td>
<td><form:errors path="prenom" cssClass="errorbox" />
</tr>
<tr>
<td id="idtab">Login :</td>
<td><form:input type="text" path="login" name="login_"
cssClass="round default-width-input" /></td>
<td><form:errors path="login" cssClass="errorbox" /></td>
</tr>
<tr>
<td id="idtab">Password :</td>
<td><form:input type="password" path="password" name="pass_"
class="round default-width-input" /></td>
<td><form:errors path="password" cssClass="errorbox" /></td>
</tr>
<tr>
<td id="idtab">Séléctionner un rôle :</td>
<td><form:select path="role">
<form:option value="" label="" />
<form:option value="ROLE_ADMIN">Administrateur</form:option>
<form:option value="ROLE_USER">Simple utilisateur</form:option>
</form:select></td>
<td><form:errors path="role" cssClass="errorbox" /></td>
</tr>
<tr>
<td id="idtab">Activé :</td>
<td><form:input type="checkbox" value="true" path="enable" />
Oui</td>
</tr>
<tr></tr>
<tr></tr>
<tr>
<td><input
class="button round blue image-right ic-right-arrow"
type="submit" value="Créer" /></td>
<td><input
class="button round blue image-right ic-right-arrow"
type="reset" value="Initialiser" /></td>
</tr>
</table>
</form:form>
Any Idea?
I'm afraid that a Validator will not be sufficient in this case. Although you could extend your AddUserValidator class to check whether the given user name is free, it will not
work in a situation in which two users simultaneously try to register using the same user name - the validation will pass, however one of the users will get an error from the database.
To protect yourself against such situations I would place the registration logic in a try catch block and in case of an error display a proper message to the user. This would be kind of an application-level validation.
Spring validator simply checks your object in accordance with the prescribed rules before you bring it into the database. It does not know anything about the database. To display the error that occurred while working with a database, you need to catch the exception manually.
In your Controller Just Check the duplication by querying from Model Repository.
#Model Entity
#Table(name = "people")
public class People {
#Column(name = "nic")
#NotEmpty(message = "*Please provide your nic")
private String nic;
#Repository
public interface PeopleRepository extends JpaRepository<People, Integer>{
People findByNic(String nic);
}
#Controller
#RequestMapping(value = "/welcome", method = RequestMethod.POST)
public ModelAndView createNewPeople(Model model,, BindingResult bindingResult) {
ModelAndView modelAndView = new ModelAndView();
People peopleExistsEmail = peopleService.findUserByNic(people.getNic());
if (peopleExistsEmail != null) {
bindingResult
.rejectValue("nic", "error.people",
"There is already a person registered with the nic provided");
}
if (bindingResult.hasErrors()) {
modelAndView.setViewName("welcome");
} else {
peopleService.savePeople(people);
modelAndView.addObject("successMessage", "People has been registered successfully");
modelAndView.addObject("people", new People());
} catch (Exception e) {
e.printStackTrace();
}
}
return modelAndView;
}
So this is the Right Answer :
The method in DAO class implementation is like that :
public boolean AddUser(User user) {
boolean t=true;
final String User_INSERT1 = "insert into utilisateurs (login, password, nom, prenom,enable) "
+ "values (?,?,?,?,?)";
final String User_INSERT2="insert into roles (login,role) values(?,?)";
/*
* On récupère et on utilisera directement le jdbcTemplate
*/
MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder("SHA");
String hash = encoder.encodePassword(user.getPassword(), "");
final String check ="select count(*) from utilisateurs where login = ?";
int result= getJdbcTemplate().queryForInt(check, new Object[]{String.valueOf(user.getLogin())});
if (result==0) {
getJdbcTemplate()
.update(User_INSERT1,
new Object[] {user.getLogin(),
hash, user.getNom(),
user.getPrenom(), user.getEnable(),
});
getJdbcTemplate().update(User_INSERT2, new Object[]{user.getLogin(),user.getRole()});
return t;
}
else { t = false ; return t;}
}
The controller :
#RequestMapping(value ="/ajouter_user", method = RequestMethod.POST)
public String add(#ModelAttribute User us,BindingResult result,ModelMap model) {
AddUserValidator uservalid=new AddUserValidator();
uservalid.validate(us, result);
if (result.hasErrors()) {
model.addAttribute("usersystem", userservice.getAllUsers());
return "gestionUser";
}else {
boolean e = userservice.AddUser(us);
if (e==false){
model.addAttribute("msg_failed","true");
}
else {
model.addAttribute("msg_success","true");}
model.addAttribute("usersystem", userservice.getAllUsers()); /*verifier*/
return "gestionUser";
}
}
And for showing the error in the jsp file :
<c:if test="${not empty msg_failed}">
<div class="errorblock">Il existe déjà un utilisateur avec cet login </div>
</c:if>
The method in DAO class implementation is like that :
public final long insert(final User user) throws MyException {
String sql = "INSERT INTO users ....";
String chkSql = "SELECT count(*) FROM users WHERE username=:username";
Map namedParams = new HashMap();
namedParams.put("username", user.getUsername());
long newId = namedTemplate.queryForInt(chkSql, namedParams);
if (newId > 0) {
try {
throw new MyException(-1);
} catch (MyException e) {
throw e;
}
}
newId = ...;// could be generated if not inc field or triggered...
namedParams.put("username", user.getUserName());
...
...
namedParams.put("id", newId);
namedTemplate.update(sql, namedParams);
return newId;
}
MyException like that:
public class MyException extends Exception{
private static final long serialVersionUID = 1L;
int a;
public MyException(int b) {
a=b;
}
}
Controller:
#RequestMapping(value = "/user", method = RequestMethod.POST)
public final ModelAndView actionUser(
final ModelMap model,
#ModelAttribute("myitemuser") #Valid final User user,
final BindingResult bindResult,
...);
...
try {
userService.addUser(user); // or dao... ;)
} catch (Exception e) {
UserValidator userValidator = new UserValidator();
userValidator.custError(bindResult);
}
UserValidator like that:
...
#Override
public final void validate(final Object object, final Errors errors) {
User user = (User) object;
...
if (user.getPassword().isEmpty()) {
errors.rejectValue("password", "error.users.emptypass");
}
}
public final void custError(final Errors errors){
errors.rejectValue("username"/* or login */, "error.users.uniqname");
}
...
Ну как то так))))

Resources