从PropertyEditor中的DB中获取实体

在Spring MVC中使用PropertyEditors时,让它们从数据库中获取实体是不是很糟糕? 我应该创建一个空实体并设置其Id。

例如,对于实体Employee:

@Entity @Table(name = "employee") public class Employee implements GenericEntity{ @Id @GeneratedValue @Column(name = "employee_id") public Integer getEmployeeId() { return employeeId; } public void setEmployeeId(Integer employeeId) { this.employeeId = employeeId; } /** More properties here **/ } 

使用以下GenericEntityEditor获取下面PropertyEditor中的Entity是一个坏主意:

 public class GenericEntityEditor<ENTITY extends GenericEntity> extends PropertyEditorSupport { private GenericDao genericDao; public GenericEntityEditor(GenericDao 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()); } } 

哪个可以绑定在控制器中:

 @Controller public class EmployeeController { /** Some Service-layer resources **/ @Resource private EmployeeDao employeeDao; // implements GenericDao genericDao @SuppressWarnings("unchecked") @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Employee.class, new GenericEntityEditor(employeeDao)); } /** Some request mapped methods **/ } 

是否首选使用EmployeeEditor更具体的方法,并让它实例化一个Employee实体并设置其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()); } } 

这样,每次在Form上存在Employee时,我们都不会对DB进行往返,但是我不确定这是否与Hibernate一样正常工作?

我认为这是合法的。 我使用这种技术已有一段时间了,效果很好。

但Spring 3.0有一个更好的概念。 所谓的转换器 (参考章节5.5 Spring 3类型转换 )

这种转换器就像单向属性编辑器一样工作。 但他们是无国籍的,因为这种更好的forms,可以被重新考虑!


补充:Spring 3.0还有一个尚未记录的function。> 3:org.springframework.core.convert.support.IdToEntityConverter

它由ConcersationServiceFactory在ConversationService中自动注册。

如果实体!! IdToEntityConverter将自动将所有(Object)转换为实体! 有一个静态方法find ,它有一个参数,返回类型是实体的类型。

 /** * Converts an entity identifier to a entity reference by calling a static finder method * on the target entity type. * * 

For this converter to match, the finder method must be public, static, have the signature * find[EntityName]([IdType]), and return an instance of the desired entity type. * * @author Keith Donald * @since 3.0 */

如果您对如何在实体中实现这样的静态查找程序方法有疑问。 然后看看Spring Roo生成的实体。