Search code examples
javamodel-view-controllersingletondaojavalin

Dao Services as Singletons?


I'm developing a web app using Javalin. I have multiple controller classes that handle my routing for me. Each controller is supposed to be associated with a single POJO/DB Table type. So for instance I have an Employee controller that routes and displays pages related to Employee POJOs. The Employee controller (on the backend) references primarily an Employee Dao Service which then queries the Employee table in the database. So far so good, right?

My question is, some of my frontend pages MUST include details from other tables, which means I am creating an instance of other DAO services within my Employee controller, for instance, sometimes I need GroupDaoService and LocationDaoService becuase several employee pages also display group and location information. I imagine this gets a little memory intensive because every time a different page is loaded, a different set of DaoServices are being used. So my question is, should these DaoServices be Singletons? Would having a single EmployeeDaoService make sense? The underlying database connection pooling class that these different DaoServices make use of, is already a Singleton. Should I follow this same pattern with my DaoServices?

Would it make sense performatively to change my DaoServices into Singletons?

Here's an example portion of the EmployeeController that will need to implement 3 or 4 other types of DAO besides EmployeeDao, which is what sparked this question.

`    public static Handler serveUserDetails = ctx -> {
         List<Integer> recCounts = mainSVC.getTotalRecords();
         Map<String, Object> pdata = new HashMap();
         String userID = ctx.pathParam(":id");
         pdata.put("numEvents", recCounts.get(0));
         pdata.put("numSites", recCounts.get(1));
         pdata.put("numUsers", recCounts.get(2));
         pdata.put("user", userSVC.getEmployee(Integer.parseInt(userID)));
         pdata.put("groups", groupSVC.getGroups());
         pdata.put("schedules", schedSVC.getSchedules());
         pdata.put("webuser", W_EMP);
         ctx.render("/templates/userdetail.vtl", pdata);
    };`

Solution

  • Yes that makes sense. Services are normally singletons. I wouldn't see a good reason to need multiple instances within a web application on a single node. If you use Spring for your dependency injection, singleton is already the default scope.

    Of course this assumes the services are stateless, i.e. don't hold session or request related data.