Behind the Pieces of a Flashcards App

We recently added a Flashcards App to NixMash Spring which you can view here. Flashcard images are displayed in a Bootstrap Carousel with a “Show Answer!” button revealing details of the image. We covered the elements that comprise the Flashcards App in the post Pieces of a Flashcards App. As you see from this post’s title, today we go a little deeper into the code behind those pieces.

Data and Entity Points of Interest

The following SQL View gives us a quick summary of the data schema, a flashcard_slides table with foreign key relationships to flashcard_categories and posts tables. Why posts? Because the Flashcard Answer is a Post object, formatted appropriately for flashcards.

Our Flashcard Entity has a @ManyToOne relationship to Posts with no reciprocal link in the Post Entity.

This means that we must explicitly persist the Flashcard object when updating it so that its Post properties are saved. This might answer the question, “Why is my @ManyToOne Parent data not updating when saving the Child Entity?”

Here’s what our Repository @Query statements look like to retrieve Child and Parent data.

To retrieve data from the SQL View we saw earlier we use Spring JPA’s @SqlResultSetMapping and @ConstructorResult. See this NixMash Post for details.

The Controller

Below is the Controller Method for displaying the Flashcard answer, which we’ve noted before is a NixMash Spring Post object. Our Flashcards are stored in Session so we can retrieve the post by the {index} value retrieved from a Ajax $.get() function we’ll see in a moment. Notice we’re returning TEXT/HTML to the client in a @ResponseBody. That HTML is formatted with our Velocity TemplateService bean.

Before leaving the MVC Controller, here’s something you may find interesting. We’re using a shared method to populate the Model Attributes for multiple endpoints. The trick is to create a Map<String, Object> object which is added in the calling method with model.addAllAttributes().

On the Client

Let’s look at how we display the Flashcard Answer. First our <button /> calling our JavaScript showAnswer() method.

Now the Ajax $.get() function calling the Controller method we saw earlier. #imageIndex provides our INDEX value which is a hidden <input /> field updated on Carousel slide movements.

Showing Carousel Slide Indicators with Thymeleaf

Before signing off, here’s something we haven’t done before, Carousel Slide Indicators with Thymeleaf. Apart from Left and Right Carousel slide arrows we wanted to add Indicators like those at the bottom center of this image.

This is pretty cool, using the Thymeleaf iterator index (row) value and th:attr to support HTML5 attributes. The dynamic quality of this approach supporting any number of slides is also quite great.

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.