Hii, I face issue in Spring Boot. Here is my question: My form & table successfully developed, but data cant stored in mysql(Spring Boot) - 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>

Related

Thymeleaf error validation: spring boot starter validation always displaying errors

build.gradle file
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
runtimeOnly 'org.postgresql:postgresql'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
implementation 'io.hypersistence:hypersistence-utils-hibernate-60:3.1.1'
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-validation', version: '3.0.1'
}
UserModel file
import jakarta.persistence.*;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.*;
#Entity
#Table(name = "users")
public class UserModel implements UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotEmpty()
private String username;
#NotEmpty(message = "Username not be Empty!")
#Size(min = 6, max = 50)
private String password;
private List<String> authorities;
private boolean isAccountNonExpired;
private boolean isAccountNonLocked;
private boolean isCredentialsNonExpired;
private boolean isEnabled;
public UserModel() {}
public UserModel(String username, String password, List<String> authorities,boolean isAccountNonExpired, boolean isAccountNonLocked, boolean isCredentialsNonExpired, boolean isEnabled) {
this.username = username;
this.password = password;
this.authorities = authorities;
this.isAccountNonExpired = isAccountNonExpired;
this.isAccountNonLocked = isAccountNonLocked;
this.isCredentialsNonExpired = isCredentialsNonExpired;
this.isEnabled = isEnabled;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> authorityList = new ArrayList<>();
return authorityList;
}
#Override
public String getPassword() {
return password;
}
#Override
public String getUsername() {
return username;
}
#Override
public boolean isAccountNonExpired() {
return isAccountNonExpired;
}
#Override
public boolean isAccountNonLocked() {
return isAccountNonLocked;
}
#Override
public boolean isCredentialsNonExpired() {
return isCredentialsNonExpired;
}
#Override
public boolean isEnabled() {
return isEnabled;
}
}
Controller file
import com.example.demo.user.UserModel;
import com.example.demo.user.UserModelRepository;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
#Controller
public class TestController {
private final UserModelRepository userModelRepository;
public TestController(UserModelRepository userModelRepository) {
this.userModelRepository = userModelRepository;
}
#GetMapping("/register")
public String showAddUserForm(UserModel userModel) {
return "register";
}
#PostMapping("/register")
public String addUser(#Valid UserModel userModel, BindingResult result, Model model) {
if (result.hasErrors()) {
return "register";
}
System.out.println(userModel);
userModelRepository.save(userModel);
model.addAttribute("users", userModelRepository.findAll());
return "home"; // TODO - This will be executed inside of our HTML
}
}
HTML file named: 'register.html'
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Register</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<!-- ${user} Object -->
<!-- *{username} Object attribute -->
<form th:action="#{/register}" th:object="${userModel}" method="post" class="form">
<div>
<input type="text" th:field="*{username}" id="username" placeholder="username" name="username">
<!-- <p th:if="${#fields.hasErrors('username')}" th:errorclass="error" th:errors="*{username}" /> -->
<p th:if="${#fields.hasErrors('username')}" th:errorclass="error" th:errors="*{username}"> </p>
</div>
<div>
<h2> Password </h2>
<input type="password" th:field="*{password}" >
<ul>
<li th:each="error : ${#fields.errors('password')}" th:text="${error}" class="error">
</ul>
</div>
<div th:if="${#fields.hasAnyErrors()}">
<ul>
<li th:each="error : ${#fields.allErrors()}" th:text="${error}"></li>
</ul>
</div>
<input type="submit" value="Add me">
</form>
</body>
</html>
Problem
Whenever i fill in my form it always displays errors whenever i click submit. Regardless if they're filled in or not.
Why is it always displaying an error?
I'm guessing that somehow, although i'm trying to render a condition, it always turns to 'false'.
I just can't see what i'm doing wrong.
Tutorial i'm following: https://www.baeldung.com/spring-thymeleaf-error-messages
Result
The problem is your UserModel it doesn't provide setter methods and thus nop data binding will (or even can) take place.
To fix either add the setter methods or tell Spring to use direct field binding.
By adding the following method to your controller you can achieve direct field binding/access.
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.initDirectFieldAccess();
}
The code above will use fields instead of properties (getter/setter pair) to do the binding. With that you can leave your UserModel unmodified and still have data binding applied.

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.

There was an unexpected error (type=Not Found, status=404). No message available : spring+ thymeleaf

i'm creating a formular to add a product_status in PostgreSql database , but i'm stacked in this erros; i think that i'm not able to send Bigdecimal value in because in the class StatusProduits the type of id is Bigdecimal, so i'm not able to add statusProduct in database because the input type dont match with the type of the ID of status_product...
this is the class:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.demo.entities;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
*
* #author G557437
*/
#Entity
#Table(name = "STATUT_PRODUITS", catalog = "", schema = "PACKOUT")
#NamedQueries({
#NamedQuery(name = "StatutProduits.findAll", query = "SELECT s FROM StatutProduits s")})
public class StatutProduits implements Serializable {
private static final long serialVersionUID = 1L;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Id
#Basic(optional = false)
#NotNull
#Column(name = "ID_STATUT_PRODUIT")
private BigDecimal idStatutProduit;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "CODE")
private String code;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "LIBELLE")
private String libelle;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 10)
#Column(name = "CREE_PAR")
private String creePar;
#Column(name = "DATE_CREATION")
#Temporal(TemporalType.TIMESTAMP)
private Date dateCreation;
#Size(max = 10)
#Column(name = "MAJ_PAR")
private String majPar;
#Column(name = "DATE_MAJ")
#Temporal(TemporalType.TIMESTAMP)
private Date dateMaj;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "idStatutProduit")
private List<Produits> produitsList;
public StatutProduits() {
}
public StatutProduits(BigDecimal idStatutProduit) {
this.idStatutProduit = idStatutProduit;
}
public StatutProduits(BigDecimal idStatutProduit, String code, String libelle, String creePar) {
this.idStatutProduit = idStatutProduit;
this.code = code;
this.libelle = libelle;
this.creePar = creePar;
}
public BigDecimal getIdStatutProduit() {
return idStatutProduit;
}
public void setIdStatutProduit(BigDecimal idStatutProduit) {
this.idStatutProduit = idStatutProduit;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getLibelle() {
return libelle;
}
public void setLibelle(String libelle) {
this.libelle = libelle;
}
public String getCreePar() {
return creePar;
}
public void setCreePar(String creePar) {
this.creePar = creePar;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public String getMajPar() {
return majPar;
}
public void setMajPar(String majPar) {
this.majPar = majPar;
}
public Date getDateMaj() {
return dateMaj;
}
public void setDateMaj(Date dateMaj) {
this.dateMaj = dateMaj;
}
public List<Produits> getProduitsList() {
return produitsList;
}
public void setProduitsList(List<Produits> produitsList) {
this.produitsList = produitsList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idStatutProduit != null ? idStatutProduit.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 StatutProduits)) {
return false;
}
StatutProduits other = (StatutProduits) object;
if ((this.idStatutProduit == null && other.idStatutProduit != null) || (this.idStatutProduit != null && !this.idStatutProduit.equals(other.idStatutProduit))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.sagemcom.tn.entities.StatutProduits[ idStatutProduit=" + idStatutProduit + " ]";
}
}
the controller :
package com.example.demo.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
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 org.springframework.web.bind.annotation.RequestParam;
import com.example.demo.dao.StatutProduitsRepository;
import com.example.demo.entities.StatutProduits;
#Controller
public class StatutProduitsController {
#Autowired
StatutProduitsRepository statutproduitsrepository ;
#RequestMapping(value="/index")
public String index( Model model,
#RequestParam(name="page", defaultValue="0")int p,
#RequestParam(name="size", defaultValue="3")int s)
{
Page<StatutProduits> pagestatutsproduits = statutproduitsrepository.findAll(new PageRequest(p,s));
model.addAttribute("listStatutProduits",pagestatutsproduits.getContent());
int [] pages = new int [pagestatutsproduits.getTotalPages()];
model.addAttribute("pages",pages);
model.addAttribute("size",s);
model.addAttribute("pageCourante",p);
return "statutproduits" ;
}
#RequestMapping(value="/form", method=RequestMethod.GET)
public String save( Model model,StatutProduits statproduit) {
statutproduitsrepository.save(statproduit);
return "Confirmation";
}
}
the HTML page :
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" type="text/css"
href="../static/css/bootstrap.min.css"
th:href="#{css/bootstrap.min.css}"
/>
<title>Statut du produit</title>
</head>
<body>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Statut d'un produit</div>
<div class="panel-body">
<form th:action="#{save}" method="post">
<div class="form-group">
<label class="control-label">ID</label>
<input class="form-control" type="number" name="id"
th:value="${statproduit.idStatutProduit}"/>
</div>
<div class="form-group">
<label class="control-label">Code</label>
<input class="form-control" type="text" name="code"
th:value="${statproduit.code}"/>
</div>
<div class="form-group">
<label class="control-label">Cree par</label>
<input class="form-control" type="text" name="creePar"
th:value="${statproduit.creePar}"/>
</div>
<div class="form-group">
<label class="control-label">Date creation</label>
<input class="form-control" type="date" name="dateCreation"
th:value="${statproduit.dateCreation}"/>
</div>
<div class="form-group">
<label class="control-label">Date maj</label>
<input class="form-control" type="date" name="DateMaj"
th:value="${statproduit.dateMaj}"/>
</div>
<div class="form-group">
<label class="control-label">Libelle</label>
<input class="form-control" type="text" name="libelle"
th:value="${statproduit.libelle}"/>
</div>
<div class="form-group">
<label class="control-label">Maj par</label>
<input class="form-control" type="text" name="majPar"
th:value="${statproduit.majPar}"/>
</div>
<div>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>

Cannot update my form in spring boot

My model is
#Entity
#Table(name = "sls_notifications")
public class SLSNotification {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(length = 11)
private Integer snumber;
#JsonFormat(pattern="yyyy-MM-dd")
#Column(nullable = false)
private Date date = new Date();
#Column(length = 8)
private String cusOffice;
#Column(length = 1)
private String cusSerial;
#Column(length = 50)
private String cusDecNo;
#JsonFormat(pattern="yyyy-MM-dd")
private Date cusDate;
#Column(length = 300)
private String manufacturer;
#Column(length = 300)
private String exporterAddress;
#Column(length = 20)
private String importerVAT;
#NotEmpty
#Column(length = 20, nullable = false)
private String declarantVAT;
private String declarantDetails;
private String vessel;
private String blNo;
private String loadingPort;
private String tradingCountry;
private String countryOrigin;
private String invoiceNo;
#JsonFormat(pattern="yyyy-MM-dd")
private Date invoiceDate;
private Double invoiceValue;
private String uom;
private Double totalQty;
private String marksNumber;
private String goodsDesc;
private String purpose;
private String hsCode;
private String issuerQltyCert;
private String qltyCertifacateNo;
private String slsNo;
private String invoiceLoc;
private String blLoc;
private String packlistLoc;
private String qcLoc;
private String otherLoc;
private String accRep;
private String accRepLoc;
#NotEmpty
#Column(length = 255, nullable = false)
private String status = "PENDING";
private String userId;
private String slsiUnit;
private String importerDetails;
private String productDesc;
private String certRefNo;
#JsonFormat(pattern="yyyy-MM-dd")
private Date blDate;
private String loadCountry;
}
My repositary is
public interface SLSNotificationRepository extends
CrudRepository<SLSNotification, Integer> {
#Override
SLSNotification save(SLSNotification slsNotification);
#Override
SLSNotification findOne(Integer snumber);
#Override
long count();
#Override
void delete(Integer integer);
#Override
void delete(SLSNotification slsNotification);
#Override
void delete(Iterable<? extends SLSNotification> iterable);
#Override
List<SLSNotification> findAll();
#Query("select a from SLSNotification a where a.slsiUnit in :unitList")
List<SLSNotification> getApplicationsByUnit(#Param("unitList")List <String> unitList);
#Query("select a from SLSNotification a where a.userId = :userId")
List<SLSNotification> getApplicationsByUserId(#Param("userId")String userId);
#Query("select a from SLSNotification a where a.slsNo = :slsNo")
SLSNotification getApplicationBySLSNumber(#Param("slsNo") String slsNo);
#Query("select a from SLSNotification a where a.importerVAT = :importerVAT group by slsNo")
List<SLSNotification> getproductByUserId(#Param("importerVAT")String importerVAT);
}
My services is
package lk.slsi.services;
import lk.slsi.domain.SLSNotification;
import lk.slsi.repository.SLSIWorkflowRepository;
import lk.slsi.repository.SLSNotificationRepository;
import lk.slsi.storage.FileSystemStorageService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import org.springframework.data.repository.query.Param;
#Service
#Scope("session")
public class ApplicationServices {
private static final Logger serviceLogger = LogManager.getLogger(ApplicationServices.class);
#Autowired
private SLSNotificationRepository slsNotificationRepository;
#Autowired
private WorkflowServices workflowServices;
#Autowired
private FileSystemStorageService storageService;
#Autowired
private FileUploadRollBack rollBack;
#Value("${slsi.filePaths.packlist}")
private String packlist;
#Value("${slsi.filePaths.qc}")
private String qc;
#Value("${slsi.filePaths.bl}")
private String bl;
#Value("${slsi.filePaths.invoice}")
private String invoice;
#Value("${slsi.filePaths.otherDoc}")
private String otherDoc;
#Value("${slsi.filePaths.accept}")
private String accept;
public boolean updateOrAddApplication(SLSNotification slsNotification,
MultipartFile attachInv,
MultipartFile attachBL,
MultipartFile attachPackList,
MultipartFile attachQc,
MultipartFile attachOther,
MultipartFile fileAccRep) {
serviceLogger.info("Staring adding/updating the SLS Notification data . data : [{}]", slsNotification);
try {
if (!attachInv.isEmpty()) {
serviceLogger.info("Uploading file : [{}]", attachInv.getOriginalFilename());
slsNotification.setInvoiceLoc(storageService.store(attachInv, invoice));
rollBack.addRollbackPoint(invoice,slsNotification.getInvoiceLoc());
}
if (!attachBL.isEmpty()) {
serviceLogger.info("Uploading file : [{}]", attachBL.getOriginalFilename());
slsNotification.setBlLoc(storageService.store(attachBL, bl));
rollBack.addRollbackPoint(bl,slsNotification.getBlLoc());
}
if (!attachPackList.isEmpty()) {
serviceLogger.info("Uploading file : [{}]", attachPackList.getOriginalFilename());
slsNotification.setPacklistLoc(storageService.store(attachPackList, packlist));
rollBack.addRollbackPoint(packlist,slsNotification.getPacklistLoc());
}
if (!attachQc.isEmpty()) {
serviceLogger.info("Uploading file : [{}]", attachQc.getOriginalFilename());
slsNotification.setQcLoc(storageService.store(attachQc, qc));
rollBack.addRollbackPoint(qc,slsNotification.getQcLoc());
}
if (!attachOther.isEmpty()) {
serviceLogger.info("Uploading file : [{}]", attachOther.getOriginalFilename());
slsNotification.setOtherLoc(storageService.store(attachOther, otherDoc));
rollBack.addRollbackPoint(otherDoc,slsNotification.getOtherLoc());
}
if (!fileAccRep.isEmpty()) {
serviceLogger.info("Uploading file : [{}]", fileAccRep.getOriginalFilename());
slsNotification.setAccRepLoc(storageService.store(fileAccRep, accept));
rollBack.addRollbackPoint(accept,slsNotification.getAccRepLoc());
}
serviceLogger.info("Saving data in the database. [{}]", slsNotification);
slsNotificationRepository.save(slsNotification);
workflowServices.initWorkflow(slsNotification.getSnumber());
return true;
} catch (Exception e) {
serviceLogger.error("Error occurred while saving SLS Common data . [{}]", e);
rollBack.rollback();
return false;
}
}
public boolean update(SLSNotification slsNotification) {
serviceLogger.info("Staring adding/updating the SLS Notification data . data : [{}]", slsNotification);
try {
serviceLogger.info("Saving data in the database. [{}]", slsNotification);
slsNotificationRepository.save(slsNotification);
return true;
} catch (Exception e) {
serviceLogger.error("Error occurred while saving SLS Common data . [{}]", e);
rollBack.rollback();
return false;
}
}
public List<SLSNotification> getAll(){
return slsNotificationRepository.findAll();
}
public SLSNotification getSLSNotificationBySerialNumnber(Integer serialNumber) {
return slsNotificationRepository.findOne(serialNumber);
}
public List<SLSNotification> getApplicationsByUserId(String userId){
return slsNotificationRepository.getApplicationsByUserId(userId);
}
public List<SLSNotification> getproductByUserId(String importerVAT){
return slsNotificationRepository.getproductByUserId(importerVAT);
}
public List<SLSNotification> getApplicationsByUnit(List <String> unitList){
return slsNotificationRepository.getApplicationsByUnit(unitList);
}
public SLSNotification getApplicationById(Integer snumber){
return slsNotificationRepository.findOne(snumber);
}
public Resource getFile(String filename){
return storageService.getFileResource(filename);
}
}
My controller is
package lk.slsi.controller;
import lk.slsi.domain.SLSNotification;
import lk.slsi.exceptions.ProductWithSameSerialExistsException;
import lk.slsi.security.domain.AuthenticatedUser;
import lk.slsi.services.ApplicationServices;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.util.SimpleFileResolver;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import static org.hibernate.annotations.common.util.impl.LoggerFactory.logger;
/**
* Created by ignotus on 2/18/2017.
*/
#Controller
#RequestMapping(path = "/")
#Scope("session")
public class ApplicationUrlMapController {
private static final Logger slsiLogger = LogManager.getLogger(ApplicationUrlMapController.class);
private static final String MESSAGE_KEY = "message";
private static final String APPLICATION_REDIRECT = "redirect:/application";
#Autowired
private ServletContext servletContext;
#Autowired
private ApplicationServices applicationServices;
#Autowired
private ProductServices productServices;
private MailService mailservice;
#Autowired
private ManufacturerServices manufacturerServices;
#Autowired
private WorkflowServices workflowServices;
#Value("${slsi.reportData}")
private String reportDataLocation;
#RequestMapping(path = "/application")
public String viewApplication(Model model) {
model.addAttribute("manu", manufacturerServices.getManufacturerListbyStatus());
model.addAttribute("edit", true);
return "application";
}
#RequestMapping(path = "/EditApplication/{snumber}",method = RequestMethod.POST)
public String addApplication(#PathVariable("snumber") #ModelAttribute("snumber") String snumber, Model model) {
model.addAttribute("app", applicationServices.getApplicationById(Integer.parseInt(snumber)));
model.addAttribute("manu", manufacturerServices.getManufacturerListbyStatus());
model.addAttribute("edit", true);
return "editApplication";
}
#RequestMapping(path = "/executeApplication", method = RequestMethod.POST)
public String registerApplication(#ModelAttribute("applicationForm") #Valid SLSNotification application,
BindingResult result,
HttpSession session,
#RequestParam("attachInv") MultipartFile attachInv,
#RequestParam("attachBL") MultipartFile attachBL,
#RequestParam("attachPackList") MultipartFile attachPackList,
#RequestParam("attachQc") MultipartFile attachQc,
#RequestParam("attachOther") MultipartFile attachOther,
#RequestParam("fileAccRep") MultipartFile fileAccRep) {
if (result.hasErrors()) {
session.setAttribute(MESSAGE_KEY, "application validation failed");
return "redirect:/application?" + MESSAGE_KEY;
}
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal != null && principal instanceof AuthenticatedUser) {
AuthenticatedUser auth = (AuthenticatedUser) principal;
application.setUserId(String.valueOf(auth.getUserId()));
}
//Setting the slsiUnit of the notification
// String sls = application.getSlsNo();
// Product p = productServices.getProductBySlsNo(Integer.parseInt(sls));
// int slsUnitNumber =p.getSlsiUnit();
//
// application.setSlsiUnit("UNIT"+ slsUnitNumber);
slsiLogger.info("Executing application update. application : [{}]", application);
if (applicationServices.updateOrAddApplication(application,
attachInv, attachBL, attachPackList, attachQc, attachOther, fileAccRep)) {
session.setAttribute(MESSAGE_KEY, "application update successful!");
} else {
session.setAttribute(MESSAGE_KEY, "application update was not successful");
}
return "redirect:/applicationManage?" + MESSAGE_KEY;
}
#RequestMapping(path = "/updateUserApplication", method = RequestMethod.POST)
public String updateApplication(#ModelAttribute("updateapplicationForm") #Valid SLSNotification slsNotification,
BindingResult result,
HttpSession session) {
slsiLogger.info("Request received to register new product. [{}]", slsNotification);
if (result.hasErrors()) {
slsiLogger.error("Rejecting the request due to binding errors, [{}]", result.getFieldErrors());
return "redirect:/applicationManage?";
}
if (applicationServices.update(slsNotification)) {
slsiLogger.info("Product registered successfully");
session.setAttribute(MESSAGE_KEY, "Product registered successfully");
} else {
session.setAttribute(MESSAGE_KEY, "Error occurred while registering the product");
}
return "redirect:/applicationManage?" + MESSAGE_KEY;
}
#RequestMapping(path = "/applicationManage")
public String viewApplicationPage(Model model) {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
long userId = 0;
String agency = "";
String units = "";
String jobroles = "";
if (principal != null && principal instanceof AuthenticatedUser) {
AuthenticatedUser auth = (AuthenticatedUser) principal;
userId = auth.getUserId();
agency = auth.getAgency();
if (agency.equalsIgnoreCase("slsi")) {
System.out.println("Agency of the User is " + agency);
model.addAttribute("applications", applicationServices.getApplicationsByUnit(auth.getJobUnits()));
} else {
model.addAttribute("applications", applicationServices.getApplicationsByUserId(String.valueOf(userId)));
}
}
return "applicationManage";
}
#RequestMapping(path = "/applicationView", method = RequestMethod.POST)
public String viewApplicationUpdatePage(#ModelAttribute("appId") String appId, Model model) {
model.addAttribute("application", applicationServices.getApplicationById(Integer.parseInt(appId)));
return "view";
}
#RequestMapping(value = "/download/{fileName}*", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<Resource> downLoadFile(#PathVariable("fileName") String filename) {
Resource file = applicationServices.getFile(filename);
return ResponseEntity
.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
.body(file);
}
#RequestMapping(path = "/viewPdf/{snumber}", method = RequestMethod.POST)
public ModelAndView getPDFReport(#PathVariable("snumber") String snumber) {
File reportsDir = Paths.get(servletContext.getRealPath(reportDataLocation)).toFile();
if (!reportsDir.exists()) {
throw ProductWithSameSerialExistsException.getInstance();
}
JRDataSource dataSource = new JRBeanCollectionDataSource(Arrays.asList(applicationServices.getApplicationById(Integer.parseInt(snumber))));
Map<String, Object> parameterMap = new HashMap<>();
parameterMap.put("datasource", dataSource);
parameterMap.put("JasperCustomSubReportDatasource", dataSource);
parameterMap.put(JRParameter.REPORT_FILE_RESOLVER, new SimpleFileResolver(reportsDir));
System.out.println(dataSource);
return new ModelAndView("pdfReport", parameterMap);
}
}
My JSP IS (EDIT JSP).I want to edit some selected fields only in my form.So i creaded new JSP for edit application,
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Application</title>
<meta charset="UTF-8">
<%#include file="template/styles.jsp" %>
<script src="${pageContext.request.contextPath}/view/public/js/jquery.min.js"></script>
<script src="${pageContext.request.contextPath}/view/public/js/jquery-ui.min.js"></script>
</head>
<sec:authorize/>
<body>
<div class="container">
<!-- Start of common header -->
<div class="row headerRow1">
<div class="col-md-12">
<jsp:include page="template/banner.jsp"/>
</div>
</div>
<div class="row">
<div class="authheader">
<%#include file="template/message.jsp" %>
</div>
</div>
<div class="col-sm-12">
<div class="row">
<div class="col-lg-12">
<div class="well lead">UPDATE NOTIFICATION FORM - SLSI ENTRY NO ${app.snumber}</div>
</div>
</div>
<div id="" style="color: red">Use Google Chrome Web browser for update your Application.</div>
<div class="row">
<!-- Start of common navigation -->
<form:form name="updateapplicationForm" id="updateapplicationForm" action="updateUserApplication" commandName="app" method="post" enctype="application/x-www-form-urlencoded">
<c:if test="${edit}">
<input type="text" id="snumber" name="snumber" value="${app.snumber}"/>
</c:if>
<div class="panel panel-default">
<div class="panel-body" >
<div class="row">
<label id="aaa" for="manufacturer" class="col-sm-2 col-form-label col-form-label-lg">Manufacturer Name &
Address <div class="req" > *</div></label>
<label id="bbb" for="manufacturer" class="col-sm-2 col-form-label col-form-label-lg">Manufacturer Name <div class="req" > *</div></label>
<div id="">
<div class="col-sm-4">
<div class="checkbox">
<label><input type="checkbox" value="" id="registered">Registered Manufacturer in SLSI</label>
</div>
<div id="regManu">
<select id="companies">
<c:forEach items="${manu}" var="com">
<option value="${com.manufacturerName}">${com.manufacturerName}</option>
</c:forEach>
</select>
</div>
<textarea name="manufacturer" class="form-control form-control-lg"
id="manufacturer"
placeholder="Enter the name & Address. Press Enter at the end of each line"
aria-descrribedby="exportertHelp" data-error="Name & Address is required!"
required rows="4" maxlength="254"></textarea>
<input type="hidden" id="manufacture" name="manufacture" value="${app.manufacturer}"/>
<div class="help-block with-errors"></div>
</div>
<label for="exporterAddress" class="col-sm-2 col-form-label col-form-label-lg">Exporter Name &
Address <div class="req"> *</div></label>
<div class="col-sm-4">
<textarea name="exporterAddress" class="form-control form-control-lg" id="exporterAddress"
placeholder="Enter the name & Address. Press Enter at the end of each line"
aria-descrribedby="exportertHelp" data-error="Name & Address is required!"
required rows="5" maxlength="254"></textarea><br/><br/>
<input type="hidden" id="exp" name="exp" value="${app.exporterAddress}"/>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row">
<br/> <label for="importerVAT" class="col-sm-2 col-form-label col-form-label-lg">Importer VAT <div class="req"> *</div></label>
<div class="col-sm-4">
<input class="form-control" type="text" name="importerVAT" id="importerVAT"
aria-describedby="importerVATHelp" placeholder="Ex : 174625588-7000 (White spaces not allowed)"
data-error="VAT number is required!" onkeyup="lettersOnly(this)" required value="${app.importerVAT}">
<div class="help-block with-errors"></div>
</div>
<label for="declarantVAT" class="col-sm-2 col-form-label col-form-label-lg">Declarant VAT <div class="req"> *</div></label>
<div class="col-sm-4">
<input class="form-control" name="declarantVAT" type="text" id="declarantVAT"
aria-describedby="declarantVATHelp" placeholder="Ex : 174625588-7000 (White spaces not allowed)"
data-error="VAT number is required!" onkeyup="lettersOnly(this)" required value="${app.declarantVAT}">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-12">
<button type="submit" id="submit" class="btn btn-success pull-right">SAVE CHANGES</button>
</div>
<div class="col-sm-3" id="msg">
<% if (message.startsWith("Registration")) {
out.print("<script>alert('" + message + "');</script>");
request.getSession().setAttribute("regMessage", "");
}
%>
</div>
</div>
</form:form>
</div>
<jsp:include page="template/footer.jsp"/>
</div>
</body>
</html>
Data retrive succecfully to the edit jsp..but when i hit sava button it will get the error..I want to update application...
Please help me.
error is
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Nov 07 12:32:42 IST 2017
There was an unexpected error (type=Internal Server Error, status=500).
For input string: "updateUserApplication"
in my netbeans console show this error
java.lang.NumberFormatException: For input string: "updateUserApplication"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[na:1.8.0_121]
at java.lang.Integer.parseInt(Integer.java:580) ~[na:1.8.0_121]
at java.lang.Integer.parseInt(Integer.java:615) ~[na:1.8.0_121]
at lk.slsi.controller.ApplicationUrlMapController.addApplication(ApplicationUrlMapController.java:81) ~[classes/:na]
at sun.reflect.GeneratedMethodAccessor842.invoke(Unknown Source) ~[na:na]
From the controller code, the API endpoint /slsi_mof/EditApplication/{snumber} is getting invoked. It is because you are using relative URL in form action. Update the form action to /slsi_mof/updateUserApplication and it should work

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.

Resources