mardi 21 mai 2019

How to handle 1:N Foreign Key for CRUD in Spring MVC / Hibernate?

I am trying to create an 'update' form for a CRUD web application. The classes related to my question are related in a 1:N manner within the MySQL database.

I am having trouble finding an elegant solution for casting the department parameter to the correct type. I could construct an ugly workaround with the form's jsp, but I would like to know what the standard SpringMVC / Hibernate solution is.

I have the following Hibernate entity classes, Employee and Department, implemented with the following code:

@Entity
@Table(name="employee")
public class Employee {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @JoinColumn(name = "ID_DEPT", referencedColumnName = "ID_DEPT")
    @ManyToOne(optional = false)
    private Department deptId;
 ...
}

The update is performed via a post request in a jsp file, as follows:

                    <form:hidden path="idEmployee" />

                    <div class="form-group">
                        <label for="deptid" class="col-md-3 control-label">Department</label>
                        <div class="col-md-9">
                            <form:input path="deptId" cssClass="form-control" />
                        </div>
                    </div>  
....

The post request will not provide the correct type for the deptId, throwing a type mismatch error.

Controller code for the saveEmployee action is:

@PostMapping("/saveEmployee")
public String saveDisciplina(@ModelAttribute("employee") Disciplina theDisciplina) {
    return "redirect:/employee/list";
}

Relevant code concerning EmployeeDAO is:

@Override
public void saveEmployee(Employee theEmployee) {
    Session currentSession = sessionFactory.getCurrentSession();
    currentSession.saveOrUpdate(theEmployee);
}

Where and how should I handle the post parameters correctly?




Aucun commentaire:

Enregistrer un commentaire