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

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.

Related

Hii, I face issue in Spring Boot. Here is my question: My form & table successfully developed, but data cant stored in mysql(Spring Boot)

Controller
Controller:
package com.isolutions4u.onlineshopping.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.isolutions4u.onlineshopping.model.Reservation;
import com.isolutions4u.onlineshopping.service.ReservationService;
#Controller
public class ReservationController {
#Autowired
private ReservationService reservationService;
#RequestMapping("/reservation")
public String reservationReg()
{
return "contactSave";
}
#RequestMapping("/saveContact")
public String saveReservation(#ModelAttribute Reservation model)
{
reservationService.saveMyUser(model);
return "contactSave";
}
}
Repository
Repository:
package com.isolutions4u.onlineshopping.repository;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.isolutions4u.onlineshopping.model.Reservation;
#Repository
public interface ReservationRepository extends CrudRepository<Reservation, Long> {
public List<Reservation> findAll();
}
Service
Service:
package com.isolutions4u.onlineshopping.service;
import javax.transaction.Transactional;
import org.springframework.stereotype.Service;
import com.isolutions4u.onlineshopping.model.Reservation;
import com.isolutions4u.onlineshopping.repository.ReservationRepository;
#Service
#Transactional
public class ReservationService {
private ReservationRepository repo;
public ReservationService(ReservationRepository repo) {
super();
this.repo = repo;
}
public void saveMyUser(Reservation reservation)
{
repo.save(reservation);
}
}
Model
package com.isolutions4u.onlineshopping.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "reservation")
public class Reservation {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String mobile;
private String email;
private String message;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Reservation(String name, String mobile, String email, String message) {
super();
this.name = name;
this.mobile = mobile;
this.email = email;
this.message = message;
}
public Reservation()
{
}
#Override
public String toString() {
return "Reservation [name=" + name + ", mobile=" + mobile + ", email=" + email + ", message=" + message + "]";
}
}
Form in localhost
fail to save
jsp location
Jsp coding :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Reservation Form</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</head>
<style>
body
{
background-color: grey;
}
.row{
margin-top: 10%;
margin-left:35%;
}
</style>
<body>
<form method="post" action="/saveContact">
<div class="row">
<div class="col s12 m6">
<div class="card white">
<div class="card-content black-text">
<span class="card-title center">Reservation Form</span>
<input type="text" placeholder="Enter the name" id="name" name="name" required/>
<input type="email" placeholder="Enter Email" id="email" name="email" required/>
<input type="text" placeholder="Enter the number" id="mobile" name="mobile" required/>
<input type="text" placeholder="Enter Message" id="message" name="message" required />
<input type="submit" value="SAVE">
</div>
</div>
</div>
</div>
</form>
</body>
</html>
Normally: store my information in the MySQL database, then this page will refresh to an empty table.
But I fail to store in my database
The above is the problem I'm having, thanks!
Console error:
2022-05-05 15:01:22.852 WARN 9356 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]
2022-05-05 15:03:33.517 WARN 9356 --- [io-8080-exec-10] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]
application-properties:
spring.datasource.url=jdbc:mysql://localhost:3307/test?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false
spring.datasource.username=root
spring.datasource.password= xxx
spring.datasource.testWhileIdle=true
spring.datasource.validationQuery=SELECT 1
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.http.multipart.max-file-size=10MB
spring.http.multipart.max-request-size=10MB
spring.http.multipart.file-size-threshold=1MB
spring.queries.users-query=select email, password, enabled from user_detail where email=?
spring.queries.roles-query=select email, role from user_detail where email=?
From the error you shared in comments, looks like you're making a HTTP POST request while the controller you've defined is for HTTP GET.
Change your controller annotations to the either of the following
#PostMapping("/saveContact")
or
#RequestMapping(path = "/saveContact", method = RequestMethod.POST)
Controller:
package com.isolutions4u.onlineshopping.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.isolutions4u.onlineshopping.model.Reservation;
import com.isolutions4u.onlineshopping.service.ReservationService;
#Controller
public class ReservationController {
#Autowired
private ReservationService reservationservice;
#RequestMapping(value="/reservation",method=RequestMethod.GET)
String addReservationForm(Model model) {
System.out.println("Add reservation Form testing 123");
model.addAttribute("reservation", new Reservation());
return"reservation_form";
}
#RequestMapping(value="/saveReservation",method=RequestMethod.POST)
String saveReservation(Reservation reservation_info) {
System.out.println("Save repository information testing 456");
reservationservice.saveReservation(reservation_info);
return"sucessful_page";
}
}
Model:
package com.isolutions4u.onlineshopping.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="reservation")
public class Reservation {
#Id
#Column(name="id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column
private String name;
private String email;
private String phone_number;
private String datetime;
private String message;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public String getDatetime() {
return datetime;
}
public void setDatetime(String datetime) {
this.datetime = datetime;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Repository:
package com.isolutions4u.onlineshopping.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.isolutions4u.onlineshopping.model.Reservation;
public interface ReservationRepository extends JpaRepository<Reservation,Long>{
}
Service:
package com.isolutions4u.onlineshopping.service;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.isolutions4u.onlineshopping.model.Reservation;
import com.isolutions4u.onlineshopping.repository.ReservationRepository;
#Service
#Transactional
public class ReservationService {
#Autowired
private ReservationRepository reservationrepo;
public void saveReservation(Reservation Reservation) {
reservationrepo.save(Reservation);
}
}
Reservation_form.jsp
<body>
<h3 style="text-align:center;">Reservation Form</h3>
<div class="row">
<div class="col s12 m6">
<div class="card white">
<div class="card-content black-text">
<table>
<form:form id="ReservationForm" modelAttribute="reservation" action="saveReservation" method="post">
<form:hidden path="id" />
<form:label path="name" for="name" >Name:</form:label>
<form:input path="name" name="name" required="required"/>
<form:label path="email" for="email" >Email:</form:label>
<form:input path="email" name="email" required="required"/>
<form:label path="phone_number" for="phone_number" >Email/Phone:</form:label>
<form:input path="phone_number" name="phone_number" required="required"></form:input>
<form:label path="datetime" for="datetime" >Reservation Date & Time</form:label>
<form:input path="datetime" name="datetime" required="required"></form:input>
<form:label path="message" for="message" >Message:</form:label>
<form:input path="message" name="message" required="required"></form:input>
<form:button name="submit" type="submit">Submit</form:button>
</form:form>
</table>
</div>
</div>
</div>
</div>
</body>

How can I update object from database without inserting new?

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" :).

Spring MVC Form not taking object path

Error shown is Bean property 'emergencyComplaint.emergencyComplaint' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
The getters and setters have the same return type, still it is showing this error.
JSP Page
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CRS | Kolkata</title>
</head>
<body>
<div>
<h1>Lodge an Emergency Complaint Now</h1>
<form:form action="" method="post" modelAttribute="people">
<form:label
path="emergencyComplaint.emergencyComplaint"
for="emergencyComplaint"
>
Emergency Complaint
</form:label>
<form:input
type="text"
name="emergencyComplaint"
id="emergencyComplaint"
path="emergencyComplaint.emergencyComplaint"
/>
<form:label
path="emergencyComplaint.status"
for="emergencyComplaintStatus"
>Status</form:label
>
<form:input
type="text"
name="emergencyComplaintStatus"
id="emergencyComplaintStatus"
path="emergencyComplaint.status"
></form:input>
<form:label path="name" for="name">Name</form:label>
<form:input path="name" type="text" name="name" id="name" />
<form:label path="phoneNumber" for="phoneNumber"
>Phone Number</form:label
>
<form:input
path="phoneNumber"
type="text"
name="phoneNumber"
id="phoneNumber"
/>
<button type="submit">Lodge</button>
</form:form>
</div>
</body>
</html>
Model Class
package com.naha.crimereportingsystem.people;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import com.naha.crimereportingsystem.emergencyComplaint.EmergencyComplaint;
#Entity
public class People {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String phoneNumber;
#OneToMany(targetEntity = EmergencyComplaint.class, cascade = CascadeType.ALL)
private List<EmergencyComplaint> emergencyComplaint;
public People() {
}
public People(long id, String name, String phoneNumber) {
this.id = id;
this.name = name;
this.phoneNumber = phoneNumber;
this.emergencyComplaint = (List<EmergencyComplaint>) new EmergencyComplaint();
}
public List<EmergencyComplaint> getEmergencyComplaint() {
return emergencyComplaint;
}
public void setEmergencyComplaint(List<EmergencyComplaint> emergencyComplaint) {
this.emergencyComplaint = emergencyComplaint;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setName(final String name) {
this.name = name;
}
}
Mapped Other Model Class
package com.naha.crimereportingsystem.emergencyComplaint;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class EmergencyComplaint {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
long id;
private String emergencyComplaint;
private String status;
public String getEmergencyComplaint() {
return emergencyComplaint;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public void setEmergencyComplaint(String emergencyComplaint) {
this.emergencyComplaint = emergencyComplaint;
}
public EmergencyComplaint(long id, String emergencyComplaint, String status) {
this.id = id;
this.emergencyComplaint = emergencyComplaint;
this.status = status;
}
public EmergencyComplaint(String emergencyComplaint, String status) {
this.emergencyComplaint = emergencyComplaint;
this.status = status;
}
public EmergencyComplaint() {
}
}
This is a valid error. Take a close look at your Entity and your modelAttribute. There is no such thing emergencyComplaint.emergencyComplaint.
So, instead of:
<form:input type="text" name="emergencyComplaint" id="emergencyComplaint" path="emergencyComplaint.emergencyComplaint" />
Try this:
<form:input type="text" name="emergencyComplaint" id="emergencyComplaint" path="emergencyComplaint" />
I do not have OneToMany example handy but I think you are smart enough to identify the issue by now while reading this. If not then to get an idea, take a look at this and this.

Spring Web Flow - Form not binding view

I'm pretty new to Spring and Spring Web Flow to be precise.
I'm running into the issue of not being able to bind the view with the form on submit :-
Here is what I have for code :-
P.s : I don't know what model={} does in the flow XML, but that's what was available in the code already, and changing it to alertForm doesn't change the behavior/
a) JSP
<form:form name="alertSubmitForm" method="post" id="alertsForm" modelAttribute="alertForm">
<table class="general">
<tr>
<th>Alert Text
</th>
<td><form:textarea path="alertText" cols="50" id="alertText" style="padding-top: 11px"></form:textarea>
</td>
<td><span id="characterCount"></span>/250
</td>
<td><br/><br/><br/><br/><br/><input id="advancedAlertOptions" type="button" value="More" class="primarybtn" style="float:right;"/></td>
</tr>
<tr class="advancedAlertOptions" style="display:none">
<th>Active Date
</th>
<td><form:input path="activeDate" id="activeDate" type="date"/>
</td>
</tr>
<tr class="advancedAlertOptions" style="display:none">
<th>Expiration Date
</th>
<td><form:input id="expDate" path="expDate" type="date"/>
</td>
</tr>
<tr class="advancedAlertOptions" style="display:none">
<th>Author
</th>
<td><form:input id="author" path="author" type="text" disabled="true" value="${author}" />
</td>
</tr>
<tr class="advancedAlertOptions" style="display:none">
<th>Added on
</th>
<td><form:input id="addedDate" type="date" path="addedDate" disabled="true"/>
</td>
</tr>
</table>
<input id="cancelAddAlert" type="button" value="Cancel" class="secondarybtn" style="float:right; margin-left:20px;"/>
<input id="persistAlert" type="submit" value="Add" class="secondarybtn" style="float:right;" name="_eventId_addAlert"/>
</form:form>
b) Flow XML
<view-state id="general" view="editMember/general" model="{}" parent="#abstract-member-view">
<on-entry>
<evaluate expression="new com.company.member.alerts.AlertForm()" result="viewScope.alertForm"/>
</on-entry>
<on-render>
<evaluate expression="alertManagementService.getAlertsList(partyIdMember)" result="viewScope.alerts" />
</on-render>
<transition on="addAlert" to="general" bind="true" >
<evaluate expression="alertManagementService.addAlertToMember(alertForm,partyIdMember)" />
</transition>
</view-state>
c) Service Call
package com.company.member.alerts;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.company.domain.db.GenericDao;
#Service("alertManagementService")
#Transactional(readOnly = true)
public class AlertManagementServiceImpl implements AlertManagementService {
#Autowired
GenericDao dao;
#Override
public List<AlertForm> getAlertsList(Long memberId) {
String a = "SELECT * FROM PARTY_ALERT WHERE PARTY_ID = "+memberId+ " ORDER BY PA_ACTIVE_DATE";
SQLQuery query = dao.createSQLQuery(a);
List<Object[]> queryResults = query.list();
List<AlertForm> results = new ArrayList<AlertForm>();
for(Object[] arr : queryResults) {
AlertForm alertForm = new AlertForm();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd H:m:s");
try {
alertForm.setAlertId(Long.valueOf(arr[0].toString()));
alertForm.setMemberId(Long.valueOf(arr[1].toString()));
alertForm.setAlertText(arr[2].toString());
Date acD = df.parse(arr[3].toString());
alertForm.setActiveDate(acD);
if(arr[4]!=null) {
Date expD = df.parse(arr[4].toString());
alertForm.setExpDate(expD);
}
alertForm.setAuthor(arr[5].toString());
Date adD = df.parse(arr[6].toString());
alertForm.setAddedDate(adD);
alertForm.setAddedDate(adD);
alertForm.setActiveDate(acD);
}
catch (ParseException e) {
e.printStackTrace();
}
results.add(alertForm);
}
return results;
}
#Override
public void addAlertToMember(AlertForm alert, Long memberID) {
Date expDate;
PartyAlerts partyAlertsDB = new PartyAlerts();
if(alert.getAlertText()!=null) {
partyAlertsDB.setAlertText(alert.getAlertText());
partyAlertsDB.setActiveDate(alert.getActiveDate());
partyAlertsDB.setMemberId(memberID);
if((expDate = alert.getExpDate())!=null) {
partyAlertsDB.setInactiveDate(expDate);
}
}
else { //hardcoding into DB
partyAlertsDB.setActiveDate(new Date());
partyAlertsDB.setInactiveDate(new Date());
partyAlertsDB.setAlertText("This is a hardcoded alert");
partyAlertsDB.setMemberId(memberID);
}
dao.save(partyAlertsDB);
}
}
d) Form Backing Bean
package com.company.member.alerts;
import java.io.Serializable;
import java.util.Date;
public class AlertForm implements Serializable{
private static final long serialVersionUID = 1L;
private Long alertId;
private Long memberId;
private String alertText;
private Date activeDate;
private Date expDate;
private Date addedDate;
private String author;
public AlertForm() {
}
public Long getAlertId() {
return alertId;
}
public void setAlertId(Long alertId) {
this.alertId = alertId;
}
public Long getMemberId() {
return memberId;
}
public void setMemberId(Long memberId) {
this.memberId = memberId;
}
public String getAlertText() {
return alertText;
}
public void setAlertText(String alertText) {
this.alertText = alertText;
}
public Date getActiveDate() {
return activeDate;
}
public void setActiveDate(Date activeDate) {
this.activeDate = activeDate;
}
public Date getExpDate() {
return expDate;
}
public void setExpDate(Date expDate) {
this.expDate = expDate;
}
public Date getAddedDate() {
return addedDate;
}
public void setAddedDate(Date addedDate) {
this.addedDate = addedDate;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
The issue is that - when I submit the form - alertForm element are NULL . The getter to get all the alerts on render works as expected.
Any help will be highly appreciated.
If you are new to SWF why are using advanced features like flow inheritance? what are the contents of the parent flow which contains the reference:
... model="{}" parent="#abstract-member-view">
This is most likely the source of your problem. You need to explicitly define the model attribute to an already initialized POJO in order to bind the form fields correctly to it.
So for testing purposes to simplify initialize a new AlertForm in the flow some where before and OUTSIDE your view-state
....
<set name="alertFormModel" value="new com.company.member.alerts.AlertForm()"/>
....
<!-- then when you enter the view-state define it like this: -->
<view-state id="general" view="editMember/general" model="alertFormModel">
....
</view-state>
if this test works then create/implement a Factory pattern for AlertForm to get rid of the ugly 'new' syntax in your flow xml

The request sent by the client was syntactically incorrect.-Spring MVC + JDBC Template

I am newbie to Spring MVC.
I was stuck by an error while running my project
Error-The request sent by the client was syntactically incorrect.
I have an entity class PatientInfo.
My jsp page is demo1.
My controller is Patient Controller.
The functionality i want to implement is Inserting values into database.
But i am not able to call my function(add-update2) in controller.
demo1.jsp
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<h2 align="center">Full Registration Form</h2>
<hr />
<table align="center" cellpadding="5" cellspacing="5">
<form:form modelAttribute="patientInfo" method="POST" action="add-update2">
<tr>
<td> First Name</td>
<td><form:input path="firstName"/></td>
</tr>
<tr>
<td>Middle Name</td>
<td><form:input path="middleName" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><form:input path="lastName"/>
</td>
</tr>
<tr>
<td>Age</td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td>Gender</td>
<td><form:select path="gender">
<form:option value="" label="Select Gender" />
<form:options items="${genderList}" itemLabel="gender" itemValue="gender" />
</form:select></td>
</tr>
<tr>
<td>Marital Status</td>
<td><form:select path="maritalStatus">
<form:option value="" label="Select Marital Status" />
<form:options items="${maritalList}" itemLabel="maritalstatus" itemValue="maritalstatus" />
</form:select></td>
</tr>
<tr>
<td>Nationality</td>
<td><form:select path="nationality">
<form:option value="" label="Select Nationality" />
<form:options items="${nationalityList}" itemLabel="country" itemValue="country" />
</form:select></td>
</tr>
<tr name="tstest">
<td>Date Of Birth</td>
<td><form:input path="dateOfBirth" name="timestamp" value=""/>
<img src="../images/cal.gif" width="16" height="16" border="0" alt="Click Here to Pick up the timestamp">
</td>
</tr>
<tr>
<td>E-mail</td>
<td><form:input path="email"/></td>
</tr>
<tr>
<td>Blood Group</td>
<td><form:select path="bloodGroup">
<form:option value="" label="Select Blood Group" />
<form:options items="${bloodList}" itemLabel="bloodgroupname" itemValue="bloodgroupname" />
</form:select></td>
</tr>
<tr>
<td><input type="submit" value="submit"/></td>
</tr>
</form:form>
</table>
</body>
</html>
Controller-PatientController.java
package com.app.ehr.api;
import com.app.ehr.domain.Bloodgroup;
import com.app.ehr.domain.Gendertype;
import com.app.ehr.entities.Patientinfo;
import com.app.ehr.domain.Maritalstatus;
import com.app.ehr.domain.Nationality;
import com.app.ehr.model.Patient;
import com.app.ehr.service.PatientService;
import org.springframework.stereotype.Controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class PatientController {
public PatientService patientService;
#Autowired
public PatientController(PatientService patientService){
this.patientService = patientService;
}
#RequestMapping(value="/", method= RequestMethod.GET)
public String index(ModelMap map) {
return "index";
}
#RequestMapping(value="/full-reg", method= RequestMethod.GET)
public String fullreg(ModelMap map,Patientinfo patientInfo) {
List<Bloodgroup> bloodList = new ArrayList<Bloodgroup>();
List<Gendertype> genderList = new ArrayList<Gendertype>();
List<Nationality> nationalityList = new ArrayList<Nationality>();
List<Maritalstatus> maritalList = new ArrayList<Maritalstatus>();
bloodList=patientService.getAllBloodgroup();
genderList= patientService.getAllGendertype();
nationalityList=patientService.getAllNationality();
maritalList=patientService.getAllMaritalstatus();
for(int i=0;i<bloodList.size();i++)
{
System.out.println("---------------------Controller"+bloodList.get(i));
}
// map.addAttribute("hello", "Hello Spring from Netbeans!!");
map.addAttribute("patientInfo", patientInfo);
map.addAttribute("bloodList", patientService.getAllBloodgroup());
map.addAttribute("genderList", patientService.getAllGendertype());
map.addAttribute("maritalList", patientService.getAllMaritalstatus());
map.addAttribute("nationalityList", patientService.getAllNationality());
return "demo1";
}
#RequestMapping(value="/add-update2", method= RequestMethod.POST)
public String addUpdate(#ModelAttribute("patientInfo") Patientinfo patientInfo) {
System.out.println("----------------------------------------- From Controller------------------------------------------------");
//patientService.addPatient(patientInfo);
return "redirect:/full-reg";
}
}
Entity Class- PatientInfo.java
package com.app.ehr.entities;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* #author HP LAPTOP
*/
#Entity
#Table(name = "patientinfo")
#NamedQueries({
#NamedQuery(name = "Patientinfo.findAll", query = "SELECT p FROM Patientinfo p")})
public class Patientinfo implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "PatientKey")
private Long patientKey;
#Column(name = "PatientMRNumber")
private String patientMRNumber;
#Column(name = "IntPrimaryPhysicianKey")
private BigInteger intPrimaryPhysicianKey;
#Column(name = "FirstName")
private String firstName;
#Column(name = "MiddleName")
private String middleName;
#Column(name = "LastName")
private String lastName;
#Column(name = "Age")
private Short age;
#Column(name = "Gender")
private String gender;
#Column(name = "Nationality")
private String nationality;
#Column(name = "DateOfBirth")
#Temporal(TemporalType.TIMESTAMP)
private Date dateOfBirth;
#Column(name = "MaritalStatus")
private String maritalStatus;
#Column(name = "Occupation")
private String occupation;
#Column(name = "AnnualIncome")
private String annualIncome;
#Column(name = "BloodGroup")
private String bloodGroup;
#Column(name = "Email")
private String email;
#Column(name = "ModeOfPayment")
private String modeOfPayment;
#Column(name = "ModeOfPaymentAlt")
private String modeOfPaymentAlt;
#Column(name = "ExtPrimaryPhysicianName")
private String extPrimaryPhysicianName;
#Column(name = "ExtPrimaryPhysicianPhoneNumber")
private String extPrimaryPhysicianPhoneNumber;
#Column(name = "IsDeleted")
private Boolean isDeleted;
#Column(name = "Meta_CreatedByUser")
private String metaCreatedByUser;
#Column(name = "Meta_UpdatedDT")
#Temporal(TemporalType.TIMESTAMP)
private Date metaUpdatedDT;
#Column(name = "Meta_CreatedDT")
#Temporal(TemporalType.TIMESTAMP)
private Date metaCreatedDT;
public Patientinfo() {
}
public Patientinfo(Long patientKey) {
this.patientKey = patientKey;
}
public Long getPatientKey() {
return patientKey;
}
public void setPatientKey(Long patientKey) {
this.patientKey = patientKey;
}
public String getPatientMRNumber() {
return patientMRNumber;
}
public void setPatientMRNumber(String patientMRNumber) {
this.patientMRNumber = patientMRNumber;
}
public BigInteger getIntPrimaryPhysicianKey() {
return intPrimaryPhysicianKey;
}
public void setIntPrimaryPhysicianKey(BigInteger intPrimaryPhysicianKey) {
this.intPrimaryPhysicianKey = intPrimaryPhysicianKey;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Short getAge() {
return age;
}
public void setAge(Short age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(String maritalStatus) {
this.maritalStatus = maritalStatus;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public String getAnnualIncome() {
return annualIncome;
}
public void setAnnualIncome(String annualIncome) {
this.annualIncome = annualIncome;
}
public String getBloodGroup() {
return bloodGroup;
}
public void setBloodGroup(String bloodGroup) {
this.bloodGroup = bloodGroup;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getModeOfPayment() {
return modeOfPayment;
}
public void setModeOfPayment(String modeOfPayment) {
this.modeOfPayment = modeOfPayment;
}
public String getModeOfPaymentAlt() {
return modeOfPaymentAlt;
}
public void setModeOfPaymentAlt(String modeOfPaymentAlt) {
this.modeOfPaymentAlt = modeOfPaymentAlt;
}
public String getExtPrimaryPhysicianName() {
return extPrimaryPhysicianName;
}
public void setExtPrimaryPhysicianName(String extPrimaryPhysicianName) {
this.extPrimaryPhysicianName = extPrimaryPhysicianName;
}
public String getExtPrimaryPhysicianPhoneNumber() {
return extPrimaryPhysicianPhoneNumber;
}
public void setExtPrimaryPhysicianPhoneNumber(String extPrimaryPhysicianPhoneNumber) {
this.extPrimaryPhysicianPhoneNumber = extPrimaryPhysicianPhoneNumber;
}
public Boolean getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(Boolean isDeleted) {
this.isDeleted = isDeleted;
}
public String getMetaCreatedByUser() {
return metaCreatedByUser;
}
public void setMetaCreatedByUser(String metaCreatedByUser) {
this.metaCreatedByUser = metaCreatedByUser;
}
public Date getMetaUpdatedDT() {
return metaUpdatedDT;
}
public void setMetaUpdatedDT(Date metaUpdatedDT) {
this.metaUpdatedDT = metaUpdatedDT;
}
public Date getMetaCreatedDT() {
return metaCreatedDT;
}
public void setMetaCreatedDT(Date metaCreatedDT) {
this.metaCreatedDT = metaCreatedDT;
}
#Override
public int hashCode() {
int hash = 0;
hash += (patientKey != null ? patientKey.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Patientinfo)) {
return false;
}
Patientinfo other = (Patientinfo) object;
if ((this.patientKey == null && other.patientKey != null) || (this.patientKey != null && !this.patientKey.equals(other.patientKey))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.app.ehr.entities.Patientinfo[ patientKey=" + patientKey + " ]";
}
}
I think the issue is that Spring doesn't know how to deserialize the date your browser client sends when submitting the following input field in
<tr name="tstest">
<td>Date Of Birth</td>
<td><form:input path="dateOfBirth" name="timestamp" value=""/>
<img src="../images/cal.gif" width="16" height="16" border="0" alt="Click Here to Pick up the timestamp">
</td>
</tr>
Spring doesn't know how to take the value that you enter into that field and convert it into a Date object. You need to register a PropertyEditor for that. For example, add the following to your #Controller class
#InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
sdf.setLenient(true);
binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
}
Obviously, change the SimpleDateFormat to whatever your client is sending.
On a related note, you're sending a 302 response by sending a redirect
return "redirect:/full-reg";
Remember that request and model attributes only live for the duration of one request. So when your client send the request to full-reg, none of the form input parameters you sent originally exist any more. You should re-think how you do this.
I came across the same error this morning. The problem with my code was that I had declared a variable as an integer in my form binding object but on the actual form I was capturing text. Changing the variable to the correct type worked out for me
This happens when the defined binding does not match to what the user is sending. The most common issues are:
Missing PathVariable declaration
Incomplete PathVariable declaration (for example missing value="variableName")
Wrong data type, such as Sotirios Delimanolis answer above. If the Class of an input parameter cannot be serialized the request is not processable
So, in general, be sure that:
Each PathVariable is declared
A value is assigned that corresponds to value to be match in the path - #PathVariable(value="myVariableName", String myVariable) where the path defines #RequestMapping(value = "/userInfo/myVariableName", method = RequestMethod.GET)
Each class declared for a PathVariable must be serializable.
try with this (with /add-update2 instead of just add-update2) and replace modelAttribute by commandName
<form:form commandName="patientInfo" method="POST" action="/add-update2">
In my case, I try to create an object that has ID and NAME as attributes.
ID is int, NAME is String.
But my js set values like this
ID = '', NAME = 'brabrabra...'
After set ID = 0, problem is fixed.
I had a similar issue recently and solved it by annotating my Date field with the #DateTimeFormat. In your case, you would edit your PatientInfo.java file to:
import org.spring.framework.annotation.DateTimeFormat;
#Column(name = "DateOfBirth")
#Temporal(TemporalType.TIMESTAMP)
#DateTimeFormat(pattern = ${pattern})
private Date dateOfBirth;
Make sure to replace ${pattern} with a string representing the format that will be received (e.g. "yyyy-MM-dd").

Resources