2

I'm developing my Course Conclusion Work (Final Graduation Work). We're using Java with Spring MVC and Glassfish Application Server only. We won't use Hibernate or JPA because we'll use stored procedures in MS SQL Server 2008, so JDBC seems to be the most effective way to call them (since, as far as I know, I can't pass an object as a parameter to SQL Server). We've configured the Datasource Pool on Glassfish. We know we'll need a DAO to call the procedures from SQL Server. My questions are:

1-) Do I need (or is it the best practice to use) a Service object (properly annoted as @Service) to call the DAO methods? Or I can just call the DAO methods right from the controller?

2-) What's the best way to get the Connection from the DataSource? A separated class with a getConnection method or ds.getConnection() on each DAO?

Thanks

BNL
  • 7,085
  • 4
  • 27
  • 32

2 Answers2

1

The biggest reasons I tend to lean towards having a service layer are for the following two reasons...

  1. Marking methods as @Transactional so all the DAO requests inside this method take place in a single transaction.

  2. I can increase the seperation of concern from the DAO and the user roles. I can mark methods as requiring certain user roles and as such it sits really nicely with Spring Security.

You can just call a DAO from the controller, but it leaves you stuck if you want to expand later on. To get the connection you can use mark the service as @Transactional and the DAO as a @Repository and Spring will handle the whole getting the session object for you and injection etc.

I tend to think (maybe incorrectly) of the service layer as a facade that gets accessed, be it from a web service or a controller or whatever, it keeps seperation.

David
  • 19,577
  • 28
  • 108
  • 128
0

Yes by all means call a dao/repository from controller, otherwise you'll end creating a laod of unnecessary classes. Spring makes it easy to make the transacation required new, so that a transaction gets created if not already present.

Use a Service when multiple DAOs/business entities are involved in one unit of work/business logic. There is no point in creating service classes for simple getters.

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311