Do I need a service object?

I design my work to complete the course (final work upon completion). We use Java only with Spring MVC application server and Glassfish. We will not use Hibernate or JPA, because we will use stored procedures in MS SQL Server 2008, so JDBC seems to be the most efficient way to call them (since, as far as I know, I can not pass an object as a SQL Server parameter). We configured the data source pool on Glassfish. We know that we will need a DAO to call procedures with SQL Server. My questions:

1-) Is it necessary (or better to use) a service object (correctly annotated as @Service) to call DAO methods? Or can I just call the DAO methods directly from the controller?

2-) What is the best way to get a connection to a DataSource? Shared class with getConnection or ds.getConnection () method for each DAO?

thanks

+2
source share
2 answers

The biggest reasons I tend to have a service level for two reasons ...

  • Labeling methods are like @Transactional, so all DAO requests inside this method are executed in a single transaction.

  • I can reinforce the concerns of the DAO and the role of the user. I can point out methods that require specific user roles, and therefore it works great with Spring Security.

You can simply call the DAO from the controller, but it will leave you stuck if you want to expand them later. To get the connection, you can mark the service as @Transactional, and the DAO as @Repository and Spring process everything, getting a session object for you and for injection, etc.

I tend to think (perhaps incorrectly) about the level of service as that it is accessed through a web service or controller or something else, it keeps the separation.

+1
source

Yes, be sure to call dao / repository from the controller, otherwise you will end up creating a laod of unnecessary classes. Spring allows you to simplify a transaction for new transactions so that a transaction is created if it is not already present.

Use the Service when multiple DAOs / business units are participating in the same business logic unit. It makes no sense to create service classes for simple getters.

0
source

Source: https://habr.com/ru/post/943692/


All Articles