When using PropertyEditors with Spring MVC, do they poorly retrieve entities from the database? Should I instead create an empty object and set its identifier.
For example, for an Employee person:
@Entity
@Table(name = "employee")
public class Employee implements GenericEntity<Integer>{
@Id
@GeneratedValue
@Column(name = "employee_id")
public Integer getEmployeeId() {
return employeeId;
}
public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}
}
It's a good idea to get Entity in the PropertyEditor below with the following GenericEntityEditor:
public class GenericEntityEditor<ENTITY extends GenericEntity<Integer>> extends PropertyEditorSupport {
private GenericDao<ENTITY, Integer> genericDao;
public GenericEntityEditor(GenericDao<ENTITY, Integer> genericDao) {
this.genericDao = genericDao;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(genericDao.findById(Integer.valueOf(text)));
}
@SuppressWarnings("unchecked")
@Override
public String getAsText() {
ENTITY entity = (ENTITY) getValue();
if(entity == null) {
return null;
}
return String.valueOf(entity.getId());
}
}
What can be connected in the controller:
@Controller
public class EmployeeController {
@Resource
private EmployeeDao employeeDao;
@SuppressWarnings("unchecked")
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Employee.class, new GenericEntityEditor(employeeDao));
}
}
It is preferable to use a more specific approach with EmployeeEditor and simply create an instance of Employee and set its id:
public class EmployeeEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
Employee employee = new Employee();
employee.setId(Integer.valueOf(text));
}
@SuppressWarnings("unchecked")
@Override
public String getAsText() {
Employee employee = (Employee) getValue();
if(employee == null) {
return null;
}
return String.valueOf(employee.getId());
}
}
This way, we don’t do a backward transition to the database every time the Employee exists in the form, but I’m not sure if this works as expected with Hibernate?
source
share