0

I want to create a controller with @ModelAttribute which allows me to insert to my Customer table data. I've done one with the employee but how can I save two hibernate mapped entities in JSP form with @ModelAttribute? also, I'm using basic generated repositories with JpaRepository interface. I want to make those two entities in relation saving it.

I tried to make @ModelAttribute JSP forms, but I don't know how to set other table entity in relation.

Employee

@Entity
@Table
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String firstName;

    private String lastName;

    @Digits(integer = 10, fraction = 0, message = "Must be a digit")
    private Integer age;

    private BigDecimal salary;

    @Temporal(TemporalType.DATE)
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @PastOrPresent(message = "Date must be past or present")
    private Date birthDate;

    @Temporal(TemporalType.DATE)
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @PastOrPresent(message = "Date must be past or present")
    private Date hireDate;

    private boolean sex; //false - woman, true - man

    @OneToOne(mappedBy = "employee")
    private Address address;

    public Employee() {

    }

    public Employee(String firstName, String lastName, Integer age, BigDecimal salary, Date birthDate, Date hireDate,
            boolean sex) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.salary = salary;
        this.birthDate = birthDate;
        this.hireDate = hireDate;
        this.sex = sex;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public BigDecimal getSalary() {
        return salary;
    }

    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }

    public Date getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }

    public Date getHireDate() {
        return hireDate;
    }

    public void setHireDate(Date hireDate) {
        this.hireDate = hireDate;
    }

    public boolean isSex() {
        return sex;
    }

    public void setSex(boolean sex) {
        this.sex = sex;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

}

Address

@Entity
@Table
public class Address {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String country;

    private String city;

    private String street;

    private Integer houseNumber;

    private Integer local;

    private String postalCode;

    @OneToOne
    @JoinColumn(name = "employee_id")
    private Employee employee;

    public Address() {

    }

    public Address(String country, String city, String street, Integer houseNumber, Integer local, String postalCode) {
        this.country = country;
        this.city = city;
        this.street = street;
        this.houseNumber = houseNumber;
        this.local = local;
        this.postalCode = postalCode;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public Integer getHouseNumber() {
        return houseNumber;
    }

    public void setHouseNumber(Integer houseNumber) {
        this.houseNumber = houseNumber;
    }

    public Integer getLocal() {
        return local;
    }

    public void setLocal(Integer local) {
        this.local = local;
    }

    public String getPostalCode() {
        return postalCode;
    }

    public void setPostalCode(String postalCode) {
        this.postalCode = postalCode;
    }

    public Employee getEmployee() {
        return employee;
    }

    public void setEmployee(Employee employee) {
        this.employee = employee;
    }

}

Controller

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    public EmployeeService employeeService;

    @Autowired
    public AddressService addressService;

    @GetMapping("/add")
    public String addUser(Model model) {
        model.addAttribute("employee", new Employee());
        return "user/addEmployee";
    }

    @PostMapping("/add")
    public String postAddUser(@Valid @ModelAttribute("employee") Employee employee, BindingResult bs) { 
        if(bs.hasErrors()) {
            return "user/addAddress";
        } else {
            employeeService.saveOrUpdate(employee);
            return "user/success";

        }
    }

    @GetMapping("/address/add")
    public String addAddress(Model model) {
        List<Employee> employees = employeeService.findAll();

        model.addAttribute("employees", employees);
        model.addAttribute("address", new Address());
        return "user/addAddress";
    }

    @PostMapping("/address/add")
    public String postAddAddress(@ModelAttribute("address") Address address, @RequestParam("employee_id") Long id) {

        Employee employee = employeeService.findById(id);
        address.setEmployee(employee);
        employee.setAddress(address);

        addressService.saveOrUpdate(address);
        employeeService.saveOrUpdate(employee);


        return "user/addAddress";
    }
}

addAddress.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>

    <head></head>

    <body>

        <h2>Address Form</h2>

        <form:form action="/user/address/add" method="POST" modelAttribute="address">
            City: <form:input path="city"/><br>
            Street: <form:input path="street" /><br>
            House Number: <form:input path="houseNumber"/><br>
            Local: <form:input path="local"/><br>
            Postal Code: <form:input path="postalCode" /><br>

            <select name="employee_id">
                <c:forEach var="employee" items="${employees}">
                    <option value="${employee.id}">${employee.id} ${employee.firstName} ${employee.lastName}</option>
                </c:forEach>
            </select><br>

            <input type="submit" />
        </form:form>
    </body>
</html>

addEmployee.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>

    <head></head>

    <body>

        <h2>Employee Form</h2>

        <form:form action="/user/add" method="POST" modelAttribute="employee">
            First Name: <form:input path="firstName"/> <form:errors path="firstName"></form:errors><br>
            Last Name: <form:input path="lastName"/> <form:errors path="lastName"></form:errors><br>
            Age: <form:input path="age" /> <form:errors path="age" type="number"></form:errors><br>
            Salary: <form:input path="salary" type="number"/> <form:errors path="salary"></form:errors><br>
            Birth Date<form:input path="birthDate" type="date"/> <form:errors path="birthDate"></form:errors><br>
            Hire Date<form:input path="hireDate" type="date" /> <form:errors path="hireDate"></form:errors><br>
            Female: <form:radiobutton path="sex" value="0" /> Male: <form:radiobutton path="sex" value="1" /><br>
            <input type="submit" value="Wyślij"/>
        </form:form>
    </body>
</html>

I need to create a result in the database with those two entities with a relationship using @ModelAttribute. Is it possible?

  • Do you want fill form for both entities, and then in controller to perform save data to db? Did I correctly understand you? Is there any code in JSP? – Anthony Aug 14 '19 at 19:31
  • yeah, i did two jsp instead of one because i don't know how to implement it, i'll update jsp in post – NewCoder255 Aug 14 '19 at 19:39

2 Answers2

0

If I understood your problem correctly, To set the associated entity -

  1. you need to have unique value to identify the entity (for ex. Employeeid for employees),
  2. fetch the details for the Employeeid, this will result in employee entity object
  3. set the employee entity object into customer entity object

similarly for Invoices. then save customer entity object.

Check - https://thoughts-on-java.org/ultimate-guide-association-mappings-jpa-hibernate/

mayank
  • 46
  • 5
  • ok i did it but hibernate allows me to create more than one address to the same user do i have to code it by myself? it wouldn't throw any errors? i updated my code is it a good way to do things like that? – NewCoder255 Aug 14 '19 at 18:22
0

You could try to combine them something like this:

    <form:form action="add" method="POST" modelAttribute="employee">
               <form:hidden path="id"/>
                First Name: <form:input path="firstName"/> <form:errors path="firstName"></form:errors><br>
                Last Name: <form:input path="lastName"/> <form:errors path="lastName"></form:errors><br>
                Age: <form:input path="age" /> <form:errors path="age" type="number"></form:errors><br>
                Salary: <form:input path="salary" type="number"/> <form:errors path="salary"></form:errors><br>
                Birth Date<form:input path="birthDate" type="date"/> <form:errors path="birthDate"></form:errors><br>
                Hire Date<form:input path="hireDate" type="date" /> <form:errors path="hireDate"></form:errors><br>
                Female: <form:radiobutton path="sex" value="0" /> Male: <form:radiobutton path="sex" value="1" /><br>

    <form:form action="add" method="POST" modelAttribute="address">
                    <form:hidden path="addressId"/>  // <- need to rename in your entity Address class               
                     City: <form:input path="city"/><br>
                    Street: <form:input path="street" /><br>
                    House Number: <form:input path="houseNumber"/><br>
                    Local: <form:input path="local"/><br>
                    Postal Code: <form:input path="postalCode" /><br>

                    <select name="employee_id">
                        <c:forEach var="employee" items="${employees}">
                            <option value="${employee.id}">${employee.id} ${employee.firstName} ${employee.lastName}</option>
                        </c:forEach>
                    </select><br>

                <input type="submit" value="Submit"/>
                </form:form>
                    <input type="submit" />
                </form:form>

In controller method:

    @PostMapping("/add")
    public String postAdd(@ModelAttribute("employee") @Valid Employee employee
                                BindingResult empBindingResult,
                                @ModelAttribute("address") Address address,
                                BindingResult addressBindingResult) {
// other code
    }

Although I didn't use radiobutton and selector elements in this combination, the rest of code should work fine.

Spring MVC Multiple ModelAttribute On the Same Form
Multiple modelattributes in a JSP with Spring

Anthony
  • 571
  • 3
  • 11