【问题标题】:Java Spring, working with Domain ObjectsJava Spring,使用域对象
【发布时间】:2013-09-09 05:37:40
【问题描述】:

我正在构建一个 Spring MVC Web 应用程序,它使用 JPA/Hibernate 来存储对象。我有一个关于域对象以及如何正确使用它们的问题。有一些具有依赖关系的域对象。例如,分配有 Region 实体的 Company 实体。

我有一个简单的辅助类,我从控制器调用,它的任务是从 URL 地址读取 XML 文件,解析其内容并根据该内容返回新的公司对象类。

class MyCustomHelper {
   MyCustomService myCustomService;

   //I have to pass myCustomService to be able to fetch existing Region entities from db
   public MyCustomHelper(MyCustomService myCustomService){
         this.myCustomService = myCustomService;
   }

   public Company createCompanyObjectFromUrl(){
       //I get these values via xml parser in the app
       String name = "Company name";
       String address = "Address of a company";
       Integer regionId = 19;

       //Create new instance of entity and fill it with data
       Company company = new Company();
       company.setName(name);
       company.setAddress(address);

       //Assign already existing region to new Company
       Region region = this.myCustomService.findOneRegion(regionId);
       company.setRegion(region);
       return company;
}

}

这种方法有效,但我不知道它的设计是对是错。如果我的 Company 对象只是没有任何依赖关系的普通对象,那么创建新 Company 并为其设置 String 和 Integer 值会很容易。但事实并非如此。

创建新公司时,我还必须创建与现有区域的连接。我通过在我的助手的构造函数中传递一个服务对象来完成它,它从数据库中获取一个现有的区域。

一旦一个新的 Company 被传回控制器,就会为其设置一些其他属性,然后将其保存到数据库中。

我觉得这不是一个很好的方法(将 Service 实例传递给辅助类)。也许在 helper 中创建某种 DTO 对象,将其返回给控制器,然后将其映射到 Domain 对象会更干净。

还是没问题?

【问题讨论】:

    标签: java hibernate spring-mvc jpa domain-object


    【解决方案1】:

    我认为 myCustomHelper 实际上命名为 ImportService 或类似名称更好,即它本身就是一个服务,可以向其中注入另一个服务。

    【讨论】:

      猜你喜欢
      • 2012-09-23
      • 2010-11-15
      • 2011-10-25
      • 2016-05-10
      • 2015-09-08
      • 2011-12-05
      • 2016-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多