2011-01-20 29 views
3

我已经看到了一些示例,说明如何使用一个没有嵌套域对象(只是基元)的域对象来执行CRUD。问题是如何对具有对其他域对象的引用的域对象做同样的事情。给下面的例子:在Struts 2中使用嵌套域对象执行CRUD的正确方法是什么?

@Entity 
public class Person implements Serializable { 
    @Id 
    private Long id; 
    private String name; 
    private Integer age; 
    private Address address; 
    private MaritalStatus maritalStatus; 
... //getters/setters 
} 

@Entity 
public class MaritalStatus implements Serializable { 
    @Id 
    private Long id; 
    private String description; 
... //getters/setters 
} 

@Entity 
public class Address implements Serializable { 
    @Id 
    private Long id; 
    private String street; 
    private String state; 
    private String zip; 
... //getters/setters 
} 

比方说,我有一个创建一个窗体或更新的人,并要求以下输入:

名称:_ _

年龄:_ ____

街道:_ __

国家:_ ____

邮编:_ __ _

婚姻状况:(与相应的按键选择输入(ID的实体)/值)

那么,y ou创建或更新具有自己的标识的嵌套属性(保存在另一个表中)。

public class PersonAction extends ActionSupport { 
    public String save() { 
     personService.save(person); 
     return SUCCESS; 
    } 

    public String update() { 
     personService.update(person); 
     return SUCCESS; 
    } 

    public void prepare() { 
     if (person.getId() != null) { 
      //find the person using the id. 
      Person p = personService.findById(person.getId()); 

      //Update the reference to the selected martial status 
      //find the maritalstatus selected from the select box 
      MaritalStatus maritalStatus = 
       maritalStatusSerivce.findById(person.getMaritalStatus().getId()); 
      //set the reference to the obtained person 
      p.setMaritalStatus(maritalStatus); 

      //find the address (in case it already exist) 
      if (person.getAddress().getId() != null) { 
       //find the address 
       Address address = addressService.findById(person.getAddress().getId()); 
       //set the reference 
       p.setAddress(address); 
      } 

      //finally set the obtained reference to the action person property 
      this.person = p; 
     } else { //New person 
      //Find the address for the person 
      if (person.getAddress().getId() != null) { 
       //Only set the reference to the selected marital status 
       //find the maritalstatus selected from the select box 
       MaritalStatus maritalStatus = 
        maritalStatusSerivce.findById(person.getMaritalStatus().getId()); 
       //set the reference to the person 
       person.setMaritalStatus(maritalStatus); 
      } 
     } 
    } 

    private Person person; 
    //getter/setters 
} 

是正确的方法:

我用的是准备方法和paramsPrepareParamsStack想这样?任何其他建议的方法?

感谢

回答

1

我有几个建议

  1. 敢问MaritalStatus和地址是否需要自己的实体。你是否曾经独立于某人的地址或婚姻状况?如果是,那么确定,如果没有,你应该让MaritalStatus和地址组件

  2. 大多数在动作的代码应该是另一个服务。我会建议创建一些协调所有这些操作的门面服务,并将它移动到一个单独的层中。我基本上是说把准备方法转到服务上。 Struts操作实际上只是调用服务,而您正在调用这些服务,但是调用服务的方式是业务逻辑,应该在服务中。操作应该只处理请求,调用业务逻辑并返回响应。你的门面服务将拥有所需的所有服务来完成它的工作。

该方法的一个好处是,您可以重新使用该操作。就目前而言,如果您想要采取其他行动来进行同样的业务运营,您需要进行一些重构。

对于您的具体问题的答案大多数在第2号 - 您创建了一个服务,它接受所有需要的参数来协调基础实体的创建和/或更新。

相关问题