Program is executing Select query is also running in console but not displaying on page,please check the program and correct me thank you
Output
Output of the Program
product class
package com.ecom.Model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#Entity
#Table(name="product")
public class Product {
#Id
#Column
private int id;
#Column
#NotNull
#Size(min=1,message="is required")
private String product_name;
#Column
#NotNull
#Size(min=1,message="is required")
private String manufacturer;
#Column
private int stock;
#Column
private String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Product(int id, String product_name, String manufacturer, int stock, String description) {
super();
this.id = id;
this.product_name = product_name;
this.manufacturer = manufacturer;
this.stock = stock;
this.description = description;
}
public Product()
{}
#Override
public String toString() {
return "Product [id=" + id + ", product_name=" + product_name + ", manufacturer=" + manufacturer + ", stock="
+ stock + ", description=" + description + "]";
}
}
product controller class
In controller i have created the model to save the data into model with the help of Product reference calling getAllProduct method.
package com.ecom.Controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ecom.DAO.ProductDAO;
import com.ecom.Model.Product;
#Controller
public class ProductController {
//injecting Dependecy
#Autowired
private ProductDAO productDAO;
#RequestMapping("/ProductList")
public String ListProducts(Model theModel)
{
List<Product> theProducts = productDAO.getAllProduct();
theModel.addAttribute("products",theProducts);
return "productlist";
}
#RequestMapping("/ProductForm")
public String ProductForm(Model theModel)
{
Product theProduct = new Product();
theModel.addAttribute("addProduct", theProduct);
return "productform";
}
#RequestMapping("/saveProduct")
public String saveProduct(#ModelAttribute("addProduct") Product theProdut)
{
productDAO.addProducts(theProdut);
return "productform";
}
}
Product Dao Implementation
package com.ecom.DAOImplementation;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.ecom.DAO.ProductDAO;
import com.ecom.Model.Product;
#Repository("ProductDAO")
public class ProductImpl implements ProductDAO {
#Autowired
private SessionFactory sessionFactory;
#Transactional
public List<Product> getAllProduct() {
Session currentSession = sessionFactory.getCurrentSession();
Query<Product> theQuery = currentSession.createQuery("from Product",Product.class);
List<Product> products = theQuery.getResultList();
return products;
}
#javax.transaction.Transactional
public void addProducts(Product theProdut)
{
Session currentSession = sessionFactory.getCurrentSession();
System.out.println("Adding Product");
currentSession.save(theProdut);
System.out.println("Success");
}
}
Jsp page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table border="1px">
<tr>
<th>ID</th>
<th>Product Name</th>
<th>Manufacturer</th>
<th>Stock</th>
<th>Description</th>
</tr>
<c:forEach var="tempCustomer" items="${products}">
<tr>
<td> ${tempCustomer.id} </td>
<td> ${tempCustomer.product_name} </td>
<td> ${tempCustomer.manufacturer} </td>
<td> ${tempCustomer.stock} </td>
<td> ${tempCustomer.description} </td>
</tr>
</c:forEach>
</table>
</body>
</html>
Just tried to set this up by creating a sample list as shown below.
#RequestMapping("/ProductList")
public String ListProducts(Model theModel)
{
List<Product> theProducts = productDAO.getAllProduct();
Product product = new Product(1,"pro-1","man-1",10,"pro-1 desc");
theProducts.add(product);
product = new Product(2,"pro-2","man-2",10,"pro-2 desc");
theProducts.add(product);
product = new Product(3,"pro-3","man-3",10,"pro-3 desc");
theProducts.add(product);
product = new Product(4,"pro-4","man-4",10,"pro-4 desc");
theProducts.add(product);
product = new Product(5,"pro-5","man-5",10,"pro-5 desc");
theProducts.add(product);
theModel.addAttribute("products",theProducts);
return "productlist";
}
The JSP page productlist.jsp is as is. No changes done. I get the output as below.
You can perhaps try putting up debug statements to see if the theProducts is correctly populated.
Related
I am new to spring MVC. To practice out my skills I made a sample form whose elements gets populated through respective controller. Now to check the validation part, I used all methodologies through annotations i.e. #NotNull, #Size, #Valid, #ModelAttribute, and BindingResult object. Below are the files I am using. I was following every necessary aspect, but don't know why am I not able to see RED colored validation messages.
Student class
package com.sikka.springmvcworking.custombeans;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Student {
private String firstName;
#NotNull
#Size(min=1,message="is required")
private String lastName;
private String country;
private String course;
private String[] knownOs;
private String[] coutries;
private Map<String,String> countryMap;
private Map<String,String> courseMap;
private Map<String,String> kosMap;
public Student() {
}
public Student(String firstName, String lastName, String country, String course, String[] knownOs, String[] coutries,
Map<String, String> countryMap, Map<String, String> courseMap, Map<String, String> kosMap) {
this.firstName = firstName;
this.lastName = lastName;
this.country = country;
this.course = course;
this.knownOs = knownOs;
this.coutries = coutries;
this.countryMap = countryMap;
this.courseMap = courseMap;
this.kosMap = kosMap;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Map<String, String> getCountryMap() {
return countryMap;
}
public void setCountryMap(Map<String, String> countryMap) {
this.countryMap = countryMap;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String[] getKnownOs() {
return knownOs;
}
public void setKnownOs(String[] knownOs) {
this.knownOs = knownOs;
}
public String[] getCoutries() {
return coutries;
}
public void setCoutries(String[] coutries) {
this.coutries = coutries;
}
public Map<String, String> getCourseMap() {
return courseMap;
}
public void setCourseMap(Map<String, String> courseMap) {
this.courseMap = courseMap;
}
public Map<String, String> getKosMap() {
return kosMap;
}
public void setKosMap(Map<String, String> kosMap) {
this.kosMap = kosMap;
}
}
Student Controller class
package com.sikka.springmvcworking.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.*;
import javax.validation.Valid;
import com.sikka.springmvcworking.custombeans.Student;
#Controller
#RequestMapping("stu")
public class StudentController {
#RequestMapping("studentForm")
public String getStudentForm(Model model) {
Student student = new Student();
Map<String,String> countryMap = new LinkedHashMap<String,String>();
countryMap.put("IN", "INDIA");
countryMap.put("BR", "BRAZIL");
countryMap.put("MX", "MEXICO");
student.setCountryMap(countryMap);
Map<String,String> courseMap = new LinkedHashMap<String,String>();
courseMap.put("java", "JAVA");
courseMap.put(".net", ".NET");
courseMap.put("php", "PHP");
courseMap.put("andr", "ANDROID");
student.setCourseMap(courseMap);
Map<String,String> kosMap = new LinkedHashMap<String,String>();
kosMap.put("win", "WINDOWS");
kosMap.put("lnx", "LINUX");
kosMap.put("mac", "MACINTOSH");
student.setKosMap(kosMap);
model.addAttribute("student", student);
System.out.println("inside STUDENT-FORM");
return "STUDENT-FORM";
}
#RequestMapping("processStudent")
public String outputStudent(#Valid #ModelAttribute("student") Student student, BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
return "redirect:studentForm";
}
return "VIEW-STUDENT";
}
}
Student Form 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" %>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style>
.error {color: red;}
</style>
</head>
<body>
<form:form action="processStudent" modelAttribute="student">
FirstName : <form:input type="text" path="firstName" placeholder="enter your first name"/><br>
LastName : <form:input type="text" path="lastName" placeholder="enter your last name"/>
<form:errors path="lastName" cssClass="error"/><br>
select country : <form:select path="coutries">
<form:options items="${student.countryMap}"/>
</form:select><br>
select course : <form:radiobuttons path="course" items="${student.courseMap}"/><br>
known OS(s) : <form:checkboxes items="${student.kosMap}" path="knownOs"/><br>
<input type="submit" value="submit">
</form:form>
</body>
</html>
Student Submit/View 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" %>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<br>
Student Name : ${student.firstName} ${student.lastName} <br>
Student visited countries:<br>
<c:forEach var="t" items="${student.coutries}">
<li> ${t} </li>
</c:forEach><br>
Known OS by student : <br>
<c:forEach var="t" items="${student.knownOs}">
<li> ${t} </li>
</c:forEach><br>
Student course : ${student.course}<br>
</body>
</html>
Every time to try lastName validation, I am leaving it blank. I am being redirected to same Student Form but with no error messages.
Is there any way to show validation error message in this jsp form.
I changed my Student Controller class to below code. Basically I used RedirectAttributes in my processStudent mapping. I also separate out the spring form element making maps to different methods. In studentForm I checked if student already exist (due to after validation process in processStudent mapping). Please see code:
Student-Controller class
package com.sikka.springmvcworking.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.util.*;
import javax.validation.Valid;
import com.sikka.springmvcworking.custombeans.Student;
#Controller
#RequestMapping("stu")
public class StudentController {
#RequestMapping("studentForm")
public String getStudentForm(Model model) {
Student student = new Student();
student.setCountryMap(getCountryMap());
student.setCourseMap(getCourseMap());
student.setKosMap(getKosMap());
if (!model.containsAttribute("student")) {
System.out.println("student not there");
model.addAttribute("student",student);
}
else {
System.out.println("student already there");
}
return "STUDENT-FORM";
}
#RequestMapping("processStudent")
public String outputStudent(#Valid #ModelAttribute("student") Student student, BindingResult bindingResult,RedirectAttributes attr) {
if(bindingResult.hasErrors()) {
attr.addFlashAttribute("org.springframework.validation.BindingResult.student", bindingResult);
student.setCountryMap(getCountryMap());
student.setCourseMap(getCourseMap());
student.setKosMap(getKosMap());
attr.addFlashAttribute("student", student);
return "redirect:studentForm";
}
return "VIEW-STUDENT";
}
private Map<String,String> getCountryMap(){
Map<String,String> countryMap = new LinkedHashMap<String,String>();
countryMap.put("IN", "INDIA");
countryMap.put("BR", "BRAZIL");
countryMap.put("MX", "MEXICO");
return countryMap;
}
private Map<String,String> getCourseMap(){
Map<String,String> courseMap = new LinkedHashMap<String,String>();
courseMap.put("java", "JAVA");
courseMap.put(".net", ".NET");
courseMap.put("php", "PHP");
courseMap.put("andr", "ANDROID");
return courseMap;
}
private Map<String,String> getKosMap(){
Map<String,String> kosMap = new LinkedHashMap<String,String>();
kosMap.put("win", "WINDOWS");
kosMap.put("lnx", "LINUX");
kosMap.put("mac", "MACINTOSH");
return kosMap;
}
}
Above approach solved my problem. I am not an expert in spring. Anyone out here can explain more deeply.
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.
Trying to return list from column named make causes error in console where column id is not found. The column named id is on the table but not sure why it is not recognized.
Car.java
package com.example.demo;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Car {
#Id
private String id;
private String make;
private String model;
private String year;
public Car() {
}
public Car(String id, String make, String model, String year) {
this.id = id;
this.make = make;
this.model = model;
this.year = year;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
}
CarRepository.java
package com.example.demo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface CarRepository extends JpaRepository<Car, String> {
#Query(value="SELECT make FROM car", nativeQuery=true)
List<Car> getAllMakes();
}
CarController.java
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
#Controller
public class CarController {
#Autowired
private CarService carService;
#Autowired
private CarRepository carRepository;
#GetMapping("/car")
public String carForm(Model model) {
model.addAttribute("car", new Car());
model.addAttribute("cars", carService.getAllCars());
return "car";
}
#PostMapping("/car")
carService.addCar(car);
return "redirect:/car";
}
#GetMapping("/list")
public String carMakeList(Model model){
model.addAttribute("list", carRepository.getAllMakes());
return "list";
}
}
list.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<h1>Car List</h1>
<table>
<thead>
<tr>
<th>Id</th>
<th>Make</th>
<th>Model</th>
<th>Year</th>
</tr>
</thead>
<tbody>
<tr th:if="${!list}">
<td colspan="2"> No Cars Available</td>
</tr>
<tr th:each="car : ${list}">
<td><span th:text="${car.make}">Make</span></td>
</tbody>
</table>
</body>
2019-08-30 10:12:31.008 ERROR 26538 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : Column 'id' not found.
2019-08-30 10:12:31.026 ERROR 26538 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; SQL [SELECT make FROM car]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query] with root cause
java.sql.SQLException: Column 'id' not found.
You need to specify *(all) in your SQL query:
public interface CarRepository extends JpaRepository<Car, String> {
#Query(value="SELECT * FROM car", nativeQuery=true)
List<Car> getAllMakes();
}
The problem is id field is required for Car entity, you can also try:
public interface CarRepository extends JpaRepository<Car, String> {
#Query(value="SELECT id,make FROM car", nativeQuery=true)
List<Car> getAllMakes();
}
For your current query to work, you can use JPA projections and change your code to:
public interface CarRepository extends JpaRepository<Car, String> {
#Query(value="SELECT make FROM car", nativeQuery=true)
List<String> getAllMakes();
}
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.
Im developing a webapp with Spring and hibernate. I have a simple form with a text field and a select:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page language="java" contentType="text/html; charset=utf8" pageEncoding="utf8" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page trimDirectiveWhitespaces="true" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="Content-Language" content="English"/>
<!-- <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="Content-Language" content="es"/>-->
<link rel="stylesheet" media="all" href="<c:url value="/resources/site.css"/>">
<title>Nuevo expediente</title>
</head>
<body>
<h2>Nuevo expediente</h2>
<form:form modelAttribute="expediente" method="post">
<table>
<tr>
<td>Tipo de expediente:</td>
<td>
<form:select path="tipoExpediente">
<form:option value="-" label="Seleccione un tipo"/>
<form:options items="${expedientes}" itemValue="tipoExpediente" itemLabel="tipoExpediente" />
</form:select>
<form:errors path="tipoExpediente" element="span"/>
</td>
</tr>
<tr>
<td>Estado:</td>
<td>
<form:input path="estado"/>
<form:errors path="estado" element="span"/>
</td>
</tr>
</table>
<br/>
<input type="submit" value="Create" />
</form:form>
</body>
</html>
The form show correctly, but when i submit, I get a HTTP Status 400 exception, with the description:
description The request sent by the client was syntactically incorrect ()..
I have read that it would be caused by requestparams, but i not using them.
Here is my controller:
package com.atlantis.atecliente.controller;
import com.atlantis.atecliente.model.Book;
import com.atlantis.atecliente.model.Expediente;
import com.atlantis.atecliente.model.TipoExpediente;
import com.atlantis.atecliente.repository.ExpedienteService;
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 java.util.List;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class ExpedienteController {
#Autowired
protected ExpedienteService service;
#RequestMapping(value = {"/*", "/expedientes"})
public String getExpedientes(Model model) {
List<Expediente> expedientes = service.getExpedientes();
model.addAttribute("expedientes", expedientes);
return "expediente";
}
#RequestMapping(value = "nuevo-expediente")
public String createExpedienteGet(Model model) {
model.addAttribute("expediente", new Expediente());
List<TipoExpediente> tiposExpediente = service.getTiposExpedientes();
// List<String> canales = service.getCanales();
model.addAttribute("expedientes", tiposExpediente);
// model.addAttribute("canales", canales);
return "nuevo-expediente";
}
#RequestMapping(value = "nuevo-expediente", method = RequestMethod.POST)
public String createExpedientePost(#ModelAttribute("expediente") Expediente expediente) {
service.createExpediente(expediente);
return "redirect:expedientes";
}
}
Finalyy the Expediente class:
package com.atlantis.atecliente.model;
import java.util.Date;
import javax.persistence.*;
#Entity
#Table(name="Expediente")
public class Expediente {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int codExpediente;
#ManyToOne
#JoinColumn(name = "tipoExpediente")
private TipoExpediente tipoExpediente;
#ManyToOne
#JoinColumn(name = "estadoExpediente")
private EstadoExpediente estadoExpediente;
#ManyToOne
#JoinColumn(name = "expedientePadre")
private Expediente expedientePadre;
#ManyToOne
#JoinColumn(name = "tipoRelacion")
private TipoRelacion tipoRelacion;
#ManyToOne
#JoinColumn(name = "canalEntrada")
private CanalExpediente canalEntrada;
#ManyToOne
#JoinColumn(name = "idiomaEntrada")
private IdiomaExpediente idiomaEntrada;
#ManyToOne
#JoinColumn(name = "idiomaSalida")
private IdiomaExpediente idiomaSalida;
#ManyToOne
#JoinColumn(name = "tipoResolucion")
private TipoResolucion tipoResolucion;
#ManyToOne
#JoinColumn(name = "canalSalida")
private CanalExpediente canalSalida;
#Column(length = 30)
private String estado;
#Column(length = 10)
private String numeroSerie;
#Column(length = 10)
private String numeroHoja;
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date fechaRedaccion;
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date fechaRecepcion;
#Column(length = 200)
private String asunto;
#Column (length = 1000)
private String descripcion;
#Column(length = 20)
private String usuarioRegistro;
#Temporal(javax.persistence.TemporalType.DATE)
private Date fechaRegistro;
#Column (length = 20)
private String usuarioModificacion;
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date fechaModificacion;
#Column (length = 20)
private String usuarioCierre;
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date fechaCierre;
public int getCodExpediente() {
return codExpediente;
}
public void setCodExpediente(int codExpediente) {
this.codExpediente = codExpediente;
}
public EstadoExpediente getEstadoExpediente() {
return estadoExpediente;
}
public void setEstadoExpediente(EstadoExpediente estadoExpediente) {
this.estadoExpediente = estadoExpediente;
}
public Expediente getExpedientePadre() {
return expedientePadre;
}
public void setExpedientePadre(Expediente expedientePadre) {
this.expedientePadre = expedientePadre;
}
public TipoRelacion getTipoRelacion() {
return tipoRelacion;
}
public void setTipoRelacion(TipoRelacion tipoRelacion) {
this.tipoRelacion = tipoRelacion;
}
public CanalExpediente getCanalEntrada() {
return canalEntrada;
}
public void setCanalEntrada(CanalExpediente canalEntrada) {
this.canalEntrada = canalEntrada;
}
public IdiomaExpediente getIdiomaEntrada() {
return idiomaEntrada;
}
public void setIdiomaEntrada(IdiomaExpediente idiomaEntrada) {
this.idiomaEntrada = idiomaEntrada;
}
public IdiomaExpediente getIdiomaSalida() {
return idiomaSalida;
}
public void setIdiomaSalida(IdiomaExpediente idiomaSalida) {
this.idiomaSalida = idiomaSalida;
}
public TipoResolucion getTipoResolucion() {
return tipoResolucion;
}
public void setTipoResolucion(TipoResolucion tipoResolucion) {
this.tipoResolucion = tipoResolucion;
}
public CanalExpediente getCanalSalida() {
return canalSalida;
}
public void setCanalSalida(CanalExpediente canalSalida) {
this.canalSalida = canalSalida;
}
public String getUsuarioRegistro() {
return usuarioRegistro;
}
public void setUsuarioRegistro(String usuarioRegistro) {
this.usuarioRegistro = usuarioRegistro;
}
public String getNumeroSerie() {
return numeroSerie;
}
public void setNumeroSerie(String numeroSerie) {
this.numeroSerie = numeroSerie;
}
public String getNumeroHoja() {
return numeroHoja;
}
public void setNumeroHoja(String numeroHoja) {
this.numeroHoja = numeroHoja;
}
public Date getFechaRedaccion() {
return fechaRedaccion;
}
public void setFechaRedaccion(Date fechaRedaccion) {
this.fechaRedaccion = fechaRedaccion;
}
public Date getFechaRecepcion() {
return fechaRecepcion;
}
public void setFechaRecepcion(Date fechaRecepcion) {
this.fechaRecepcion = fechaRecepcion;
}
public String getAsunto() {
return asunto;
}
public void setAsunto(String asunto) {
this.asunto = asunto;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public Date getFechaRegistro() {
return fechaRegistro;
}
public void setFechaRegistro(Date fechaRegistro) {
this.fechaRegistro = fechaRegistro;
}
public String getUsuarioModificacion() {
return usuarioModificacion;
}
public void setUsuarioModificacion(String usuarioModificacion) {
this.usuarioModificacion = usuarioModificacion;
}
public Date getFechaModificacion() {
return fechaModificacion;
}
public void setFechaModificacion(Date fechaModificacion) {
this.fechaModificacion = fechaModificacion;
}
public String getUsuarioCierre() {
return usuarioCierre;
}
public void setUsuarioCierre(String usuarioCierre) {
this.usuarioCierre = usuarioCierre;
}
public Date getFechaCierre() {
return fechaCierre;
}
public void setFechaCierre(Date fechaCierre) {
this.fechaCierre = fechaCierre;
}
public TipoExpediente getTipoExpediente() {
return tipoExpediente;
}
public void setTipoExpediente(TipoExpediente tipoExpediente) {
this.tipoExpediente = tipoExpediente;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
}
Some help?
Thanks
I have resolve this issue. The problem was with the controller method mapping to the url.
I modified the function createExpedientePost to:
public String createExpedientePost(#ModelAttribute("expediente") Expediente expediente, BindingResult result) {
The change was the addition of BindingResult as an argument.
I hope this may help others.
It seems somebody can get such error status, when arguments for a controller method were set incorrectly.
For instance I had the same because of wrong name of referer header(It was called as referrer)
public String foo(#RequestHeader(value = "referer") final String referer) {}