Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Accessing the Database From a Thymeleaf Template

DZone's Guide to

Accessing the Database From a Thymeleaf Template

It breaks MVC, but accessing a database from Thymeleaf is certainly possible. But would you want to?

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

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.

Spring MVC CourseThe 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.

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:
template ,java ,spring mvc ,principles ,thymeleaf ,mvc

Published at DZone with permission of John Thompson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}