javaspring-data-jpadata-access-layerdata-layers

Entity assemblage in different layers


Let's assume I have the following classes:

@Entity
public class Book {
...
}

@Repository
public class BookRepositoryImpl implements BookRepository {    
...
}

@Service
public class BookServiceImpl implements BookService {
...
}


@Entity
public class Author{
...
}

@Repository
public class AuthorRepositoryImpl implements AuthorRepository {
...
}

@Service
public class AuthorServiceImpl implements AuthorService {
...
}

Now i want to save a book with an author. To my BookService i pass somehow BookDto with all information except author, and as second parameter i pass author Id. Now to save my book i have to assemble Book entity. Which layer is the correct one to create it? i see few possibilities but im not sure which approach is the correct one:

Which approach is the correct one and why? It would seem to me that a logical solution is the first one, however i don't like the idea of mixing entity assemble with some business logic that might be inside of my services. Is there a pattern to separate business logic from technical solutions?


Solution

  • You can use BookingService.createBook to assemble data. Because a book must have at least one author. And service layer is for business logic. You need to specify all data into this layer. You can call AuthorRepository from AuthorService but you have to call AuthorService from BookService . Because BookService can not directly use AuthorRepository. So define a method on AuthorService to get author by ID and from BookService call AuthorService service method . You can access every repository by it's service layer because to get data, every service have some logic behind this data to return. Every Service layer is responsible for its repository layer.

    So define AuthorService.findAuthorById(long id) and then call this method from BookService and assemble data at bookservice.