This week, I had a student ask me how they could use a Java function to access the database from a Thymeleaf template. Thymeleaf is a modern templating engine. And accessing the database directly from Thymeleaf is certainly something you could do. But is it really something you want to do?
I’ve worked for a couple major retailers which had JSP templates accessing the database with static Java methods. It was not a good thing.
When you’re using Thymeleaf with Spring MVC, you’re following the MVC design pattern. MVC is Model, View, Controller. The Thymeleaf template is the ‘View’. The Spring controller will return a model to the Thymeleaf template engine. The model should be a data structure. Nothing more.
The MVC design pattern is elegant and widely accepted design pattern. I personally like how the MVC design pattern is in alignment with the SOLID Principles of Object Oriented Design.
If you choose to access the database directly from Thymeleaf, you break the separation of concerns. You’re violating the SOLID principles of Object Oriented Design.
I took the time to record a brief video about why accessing the database from Thymeleaf is a very bad idea. You can see the video here on YouTube.
While I could certainly show you how to access the database from a Thymeleaf template, I won’t. I hope you watch the above video to see why this is such a poor programming practice.