The first primary feature of NixMash Spring v0.3.5 is Posts A-to-Z listing all posts grouped by their first letter or digit. This required two logical components: 1) A smart alphabetic navigation list which highlights the letters with associated posts, and 2) Posts ordered and grouped by their first letter.
In this post we’ll look at how the Alphabetic Navigation bar was created in Spring and Thymeleaf. You’ll notice that the navigation bar letters which have posts (like “C”) are enabled, while those with no items are disabled. You’ll also notice a “0-9” category beginning the list. Posts starting with any digit will display in that area.
A container called AlphabetDTO will really simplify the process for us. We’ll be seeing it several times so here’s a quick look at it.
Service Logic: Populating List<AlphabetDTO>
We’re going to send a list of our AlphabetDTO objects to the web page through our MVC Controller, but all of the heavy logic happens in the Service Layer. There are a number of comments to help us walk through the code. The main points to know begin with a string from our PostRepository containing the distinct first letters and numerals of our Post Titles which we’ll compare against a complete alphabetic list.
We return our AlphabetDTO list with each letter and its active/inactive Boolean designation. We add the “0-9” AlphabetDTO key and set its active value based on the presence of any digits in the SQL String.
Retrieving the AlphaNumeric String of Title First Letters in SQL
Here’s the SQL for retrieving the distinct first letters or numbers of all of the Post Titles from SQL. What’s really cool here is that we can do this with a single SQL statement. Something else very cool about this bit of code is Spring JPA’s nativeQuery property, allowing us to easily drop a SQL Native Query in our PostRepository.
Not much happening here, but the beauty is in the simplicity of it.
Thymeleaf gets the ball at this point, iterating over the AlphabetDTOs and enabling or disabling each AlphabetDTO alphaKey link based on its active status.
There is one test which is pretty interesting. Our H2 Data contains several posts which begin with a digit, so the “0-9” alphaKey in List<AlphabetDTO> should be set to true. There are a lot of references out there on testing if a List<> contains a property with a specific value, but few on testing multiple values in a single list element. Here’s how we test the list element with “0-9” is set to true.