Question

I am building a Spring MVC web application, which uses JPA/Hibernate to store objects. I have a question which is regarded to domain objects and how to use them correctly. There are some domain objects with dependencies. An example can be a Company entity which has a Region entity assigned to it.

E-R relation diagram

I have a simple helper class which I call from controller, which task is to read a XML file from URL address, parse its content and return new Company object class based on that content.

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;
}

}

This approach works,but I do not know whether it is right or wrong by design. If my Company object was only plain object without any dependencies, it would be easy to create new Company and set just String and Integer values to it. But that's not a case.

I have to also create connection to existing Region when creating new Company. I have done it by passing a service object in constructor of my helper, which fetches an existing Region from database.

Once a new Company is passed back to controller, there are is some other attributes set to it and then it is saved into database.

I have a feeling that this is not a very good approach (passing Service instance to helper class). Maybe it would be cleaner to create some kind of DTO object in helper, return it back to controller and then map it to Domain object.

Or it is just OK?

Was it helpful?

Solution

I think myCustomHelper is actually better named ImportService or similar, ie its a service itself and it is fine to inject another service into it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top