fuj*_*ujy 5 java spring hibernate spring-webflow
我应该绑定到一个复杂对象的形式,装载这种形式我必须初始化所有的孩子,只有有很多的方法,对象之前包裹了很多孩子,每次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,
}
Run Code Online (Sandbox Code Playgroud)
编辑:
根据以下答案,似乎没有最佳答案.但是,我可以使用实体constructor
或Factory
设计模式.
但是这两个解决方案都没有解决我在使用Required和Optional字段初始化所有字段策略时的其他问题.
例如:如果我有所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());
Run Code Online (Sandbox Code Playgroud)
您可以向实体添加构造函数(毕竟它们是它们的角色),如果具有空值对您的案例没有意义,则可以实例化这些字段.
另一种方法是,如果你不喜欢添加构造函数,那就是添加一个静态工厂方法来实现你的bean,它看起来像initializeEmployee()但有潜在的参数并返回一个Employee对象.http://en.wikipedia.org/wiki/Factory_method_pattern
同样,您也可以实例化您的集合,因为对于空集合可能没有任何意义(但是有一个用于空集合).
您可以向实体添加行为,不要锁定在Anemic Domain Model中,这被Martin Fowler视为反模式http://www.martinfowler.com/bliki/AnemicDomainModel.html
编辑
我看到你正在使用dao.persist(实体):你可能正在使用JPA.如果是这样,也许最好不要修改你的对象图(在正面)并为Employee添加一个EntityListener(在持久层中):这里是Hibernate EntityListener的链接(它是一个JPA特性,所以如果你是使用另一个框架不用担心)http://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/listeners.html
使用EntityListener,您可以在持久性和之后添加小的"aop like"操作.这将允许您不处理域和前层上的空值,并确保每个实体都适合任何情况(更好的验证).
在PrePersist中:你们添加你的代码来检查空值(可能在域类上使用自定义方法"isEmpty()")并在需要时使字段无效.在PostPersist中添加新对象.
归档时间: |
|
查看次数: |
1398 次 |
最近记录: |