HibernateJavaSpring,处理域对象
我正在构建一个SpringMVCWeb应用程序,它使用JPA/Hibernate来存储对象。我有一个关于域对象以及如何正确使用它们的问题。存在一些具有依赖关系的域对象。例如,公司实体分配了一个区域实体
我有一个简单的助手类,我从controller调用它,它的任务是从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;
}
}
这种方法是有效的,但我不知道它在设计上是对还是错。如果我的公司对象是唯一没有任何依赖项的普通对象,那么创建新公司并只为其设置字符串和整数值就很容易了。但事实并非如此
在创建新公司时,我还必须与现有地区建立联系。我通过在助手的构造函数中传递一个服务对象实现了这一点,它从数据库中获取一个现有区域
一旦一个新公司被传回控制器,就会有一些其他属性设置给它,然后它被保存到数据库中
我觉得这不是一个很好的方法(将服务实例传递给helper类)。也许在helper中创建某种类型的DTO对象,将其返回控制器,然后将其映射到域对象会更干净
还是就这么好
# 1 楼答案
我认为myCustomHelper实际上更好地命名为ImportService或类似的服务,即它本身就是一个服务,可以向其中注入另一个服务