【发布时间】:2013-09-21 18:13:18
【问题描述】:
我有一个表单应该绑定到一个包含很多子对象的复杂对象,每次在加载这个表单之前我都必须在一个只有很多 new 语句的方法中初始化所有子对象并调用setter 方法,我必须为很多表单和其他复杂对象重复这个场景
有比initializeEmployee 方法更好的策略吗?
例如:
@Entity
public class Employee {
Integer Id;
Contract contract;
Name name;
List<Certificate> list;
// getter and setters
}
@Entity
public class Contract {
String telephoneNum;
String email;
Address address;
// getter and setters
}
@Entity
public class Address {
String streetName;
String streetNum;
String city;
}
public class Name {
String fName;
String mName;
String lName;
// getter and setters
}
// And another class for certificates
public initializeEmployee() {
Employee emplyee = new Employee();
Name name = new Name();
employee.setName(name);
Contract contract = new Contract();
Address address = new Address();
contract.setAddress(address);
employee.setContract(contract);
// set all other employee inner objects,
}
编辑:
根据以下答案,似乎没有最佳答案。但是,我可以使用实体 constructor 或 Factory 设计模式。
但是这两种解决方案都不能解决我在使用必填和可选字段初始化所有字段策略时遇到的其他问题。
例如:
如果我根据需要有Name(即,如果Name 对象属性为空,则不会保留Employee 实体,另一方面,Contract 实体是可选的。我不能将空的Contract 对象持久保存到数据库中,所以我必须在持久化之前先将其设为null,然后在持久化之后重新初始化它,如下所示
// Set Contract to null if its attributes are empty
Contract contract = employee.getContract()
if(contract.getTelephoneNum().isEmpty && contract.getEmail().isEmpty() && contract.getAddress().isEmpty()){
empolyee.setContract(null);
}
employeeDAO.persist(employee);
// reinitialize the object so it could binded if the the user edit the fields.
employee.setContract(new Contract());
【问题讨论】:
-
我不太确定这是什么意思。为什么初始化一个空对象或默认对象会更好(甚至更可取)?
-
@MikkelLøkke 因为 Spring Webflow 需要初始化对象来绑定其属性,否则会引发空指针异常。
-
@fujy Mikkel 想说的是,如果不需要空的 Employee 对象,那么您不应该让用户在不提供所有必需字段的情况下实例化它。
标签: java spring hibernate spring-webflow