0

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 <a href="<c:url value='/list' />">List of All Employees</a> </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

5
  • sure..here is my controller code Commented May 10, 2017 at 10:45
  • I have added my controller code in main post. U can see the main post and will get the code Commented May 10, 2017 at 10:50
  • please post only relevant code. Only method in which u want to save the table details Commented May 10, 2017 at 11:03
  • 1
    What u can do is, In your controller method I think u will get employee object.So using it create one service and save only user_name ,password.After that call another service which save rest of the data into other table Commented May 10, 2017 at 11:07
  • I tried it before. But i was getting that error. org.springframework.beans.NotReadablePropertyException: Invalid property 'user_name' of bean class [com.websystique.springmvc.model.Employee]: Bean property 'user_name' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter? Commented May 10, 2017 at 11:09

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.