Coders Campus Podcast

Coders Campus Podcast

Download on the App Store

Coders Campus Podcast episodes

  • EP05 – JSPs are extinct and Thymeleaf is the Culprit

    You see, JSPs are essentially hybrids. They are a way for coders to create HTML and mix in some Java.

    Now, way back when JSPs were first created, you could embed native Java code right onto your JSP (read: onto your presentation layer).

    This has quickly been labelled as a horrendous programming practice that should be avoided at all costs.

    Fair enough…

    But we still continued to use JSPs and instead used tag libraries to add additional markup to our JSP code.

    For example, we would use something like the “C” JSTL (a tag library for JSPs) in order to introduce some control structures and additional functionality.

    This was a much better approach than using plain old Java code embedded right onto JSPs, but it still wasn't the greatest solution.

    The reason why this wasn't a great solution was because we are still using non-native HTML code inside of our HTML pages (well… We call them JSPs, but they're essentially just HTML pages).

    Remember that the convention is to separate your concerns as best as possible… Which is why we tend to put our CSS and JS code in external files and link them up inside our HTML / JSPs.

    So why is it that we're allowed to use glorified Java code in our JSPs, but not anything else?

    The Main Issue with JSPs

    Okay fine, if we drop the argument that we should separate our concerns, then why else are JSPs a bit crappy?

    Well, they can't really be opened outside of the web server context.

    What happens if you shut down your web server, then try to access a JSP?

    Or what happens if you just try to open a plain old JSP inside of your browser?

    I bet you it's not going to look like it should.

    That's because JSPs rely on the web server to render properly.

    So how can we write native HTML code, but still be able to have our HTML pages properly interact with our back-end server?

    Enter Thymeleaf

    First thing's first. Let's all get on the same page with how to pronounce Thymeleaf.

    It's “Time – Leef”. Thyme is pronounced like the herb, which is pronounced “Time”, like the time of day.

    Awesome, now that SUPER important detail is out of the way…

    Thymeleaf solves all the problems that have plagued JSPs since the beginning of time.

    With Thymeleaf you can write native HTML code that any old browser would be able to render, and yet still be able to interact as you always could, with your Java server.

    Boo yah!

    And, thankfully, it's not too tough to learn.

    I plan on teaching you most of what you need to know in this one post.

    Getting Started with Thymeleaf

    This can either be ridiculously simple… Or it can be simple.

    Either way, getting up and running with Thymeleaf is easier than putting on my socks in the morning.

    Are you using Spring Boot?

    If you're using Spring Boot, then you're already good to go. You literally don't have to do anything to start using Thymeleaf.

    Ridiculously simple right?

    Okay, but what if you aren't using Spring Boot.

    Well then it's as simple as either putting in an artifact into your dependency management system (i.e. adding a dependency into your Maven pom.xml file) or just manually downloading the JAR and adding it to your classpath.

    There are some really simple installation instructions via the Thymeleaf download page.

    So, for example, if you're not using Spring Boot but you're still working with a Spring based project, then you'd add the core library plus the appropriate Spring version integration. Let's assume you're working with Spring 4 without Spring Boot, here's what you would add to your maven pom.xml file:

    org.thymeleaf
    thymeleaf
    3.0.0.RELEASE
    org.thymeleaf
    thymeleaf-spring4
    3.0.0.RELEASE
    Thymeleaf Syntax

    Alright, so you've installed Thymeleaf, now what?

    Well, it's time to start writing some code.

    For my code, I'm going to assume we're working within the confines of our Food Diary application that we've been building over the past few weeks.

    Note: You can check out the GitHub repository for this project here.

    Simple IF Statements in Thymeleaf

    We'll base this on whether or not there is a list of FoodDiary objects on our model.

    ...

    The first thing I'll mention (and this is the only time I'll mention it): you'll need to define the “th” xml namespace by adding xmlns:th="http://thymeleaf.org" to the tag. When you do this, you won't get any warnings in your IDE saying that the thymeleaf attributes are not found.

    Okay having said that, let's continue… Please note that in the code above, it isn't the most efficient way of trying to iterate through collections, as the check to see if it's not null can be done when iterating.

    How to Iterate Over Collections with Thymeleaf

    This one's got a slightly strange syntax, most of the code you'll write with Thymeleaf will be wrapped entirely within the Spring Expression Language syntax (SPEL for short)… this syntax is the dollar sign followed by curly brackets “%{}”.

    But when performing a for each type loop with Thymeleaf it's just a bit different. Here's how we would iterate through our foodDiaries:

    Displaying Information from Model with Thymeleaf

    Next up is something we do all the time… display the information we have on our model.

    In Thymeleaf there are two main ways of accomplishing this task… the first is with th:text like so:

    The use of th:text plus String concatenation will result in a String like this: “I had pizza for dinner at 6:00pm”.

    The th:text attribute can be used within many tags too, not just a div. You can use it in span tags, header tags, li tags… you name it.

    That's the beauty of Thymeleaf, a lot of their attributes can be used with many tags.

    Now, constantly writing th:text="" inside of span and/or div tags would get a bit tiresome if there was a lot of outputting that needed to be done.

    So Thymeleaf addresses this by allowing in-lining of outputs like so:

    I had [[${aFoodDiaryObj.food}]] for [[${aFoodDiaryObj.mealType}]] at [[${aFoodDiaryObj.timeOfDay}]]
    Linking HTML Elements to Model Attributes with Thymeleaf

    Alright, so we're moving right along with this Thymeleaf syntax. Next up is something else that's critical to building web applications… how to link your input elements to your Spring Controllers so that you can transfer data from HTML to Java.

    Let's assume that we want to populate a FoodDiary object in HTML and have it link to our Java back-end.

    Previously, when using JSPs we would make use of the form JSTL and we would create elements.

    Well, once again, Thymeleaf is supposed to be able to be interpreted by a browser without the use of a running web server. So a browser doesn't know what the heck a element is without something like a Tomcat server.

    Thymeleaf just uses its th:field syntax to link everything up.

    Note: Let's assume that we have a foodDiary item that's been added to our model from a controller.

    Food:
    Meal Type:
    Time of Day:
    Cost:

    As you can see, we're using the name of the variable that's been added to our model (foodDiary) inside of our reference to th:field in order to link everything up with our controller.

    Now when we submit this form (assuming our controller is properly hooked up), the Java method that's called will be able to translate this HTML form data into an actual FoodDiary Java object.

    Mission accomplished!

    But, we're not done yet… there's a small shortcut that you can use to make your life just a little bit easier.

    You can make use of a th:object attribute to sort of “store” a reference to a model attribute when you're using the th:field code.

    This is merely a way to reduce the amount of keystrokes you need to make… so there's literally no difference in functionality here… it's all about sheer laziness!

    This code would work in exactly the same way as the code above:

    Food:
    Meal Type:
    Time of Day:
    Cost:

    So the two things to note above are:

    1. We used the th:object attribute on the form to “store” the reference to the model attribute
    2. We used the *{} syntax as opposed to the ${} and we omitted the reference to the model attribute to save keystrokes
    3. Again, all the code above does is saves you from having to type ${foodDiary.someProperty} and instead replaces it with *{someProperty}.

      Utility Objects in Thymeleaf

      From time to time we've all needed to go searching for the tag library that will help us format a date / currency or some other random utility based task that the standard “C” or “FORM” tag libraries couldn't help us with.

      Well, thankfully the good folks at Thymeleaf thought of this and they provide many expression utility objects.

      Here's a quick example of how you could format a date:

      Today is:

      Or how about checking to see if a list is not empty?

      How to use Thymeleaf as it was Intended to be Used…

      Now, if you're an established Thymeleaf user, and you've been using it properly… you might be a little upset with my tutorial thus far. Rightfully so, I've left out one of the key reasons for which Thymeleaf was created.

      You see, Thymeleaf was created so that you could open up an HTML file with a whole bunch of Thymeleaf markup in it, but the page would still open up and look fairly normal. Meaning, you don't have to view a Thymeleaf enabled HTML page with a server running.

      But if you don't have a server running, and Thymeleaf is a server based library, then how will your HTML page look right?

      Well, through clever use of default values.

      You see, whenever you create a Thymeleaf enabled HTML element, you should also provide some sort of default value so that if you were to open the HTML page without a server running, it could fall back to those defaults.

      Let me show you an example:

      Welcome to my Website
      I ate cookies

      Do you notice how we hard-coded some text in the code above?

      We put in “Welcome to my Website” in the h1 tag and we also put “I at cookies” in the span tag.

      And what you'll notice is that if you were to open that up in a browser without a server running, you would see exactly those two sentences displayed on the screen… because the browsers will just ignore the thymeleaf markup completely. And if you ignore the Thymeleaf markup, then you're left with a plain old page that welcomes you and tell you that it ate cookies.

      However, if you open this page while a web server is running with Thymeleaf enabled, Thymeleaf will recognize its own markup and it will replace the “default” values you supplied with the expected data that exists on the model.

      Pretty neat stuff.

      You can even use Thymeleaf in JavaScript as well.

      Using Thymeleaf in JavaScript

      Let's assume you'd like to get access to some values that are on the model, but you're inside of a JavaScript code snippet.

      No problemo!

      You just need to use the th:inline="javascript" attribute along with some CDATA markup to make everything work.

      It's a bit convoluted, but hey, it works!

      Here's how I would get the value of a property from the model assuming there's a foodDiary object available to work with:

      So there are three main things you need to take note of here:

      1. Make sure you use the th:inline="javascript" code in your script tag.
      2. Don't forget to include the opening and closing CDATA markup inside your script tag.
      3. It's recommended to comment out the inlined code in your JavaScript so that Thymeleaf can make use of default values.
      4. In the end, you can get away with NOT commenting out your inlined Thymeleaf code, but then you wouldn't really be using good practices with your Thymeleaf code.

        So for the sake of completion, here's what the above code would look like if you weren't using proper Thymeleaf coding principles:

        Again, both of the code snippets above accomplish the same overall task, the only difference is that the second code snippet won't work as well when you're loading the page outside of a running web server.

        Contructing Dynamic URLs with Thymeleaf

        At some point in your web application coding journey, you will likely run into the situation where you'll need to generate a dynamic URL.

        Meaning, you'll need to create a URL that contains information that will vary depending on the situation.

        A very common scenario is one where you want to click on a link to see more information about a specific row in your database.

        So for our specific scenario, let's say we want to have a page that lists out links to all of our FoodDiary items.

        Dinner: Pizza

        Alright, so this syntax is also a bit strange, but you can figure it out with some of my expert teaching *wink wink, nudge nudge*.

        First thing to note is that we use the “at” syntax for URLs: @{...}. This is a special syntax just for URLs because they are THAT important.

        Next thing you'll see is that we've introduced a th:href syntax for Thymeleaf URLs. The th:href attribute is what enabled the use of the @{...} notation.

        Note: if you are an astute coder, you might be asking yourself a question: “If I can use th:href does that mean I can throw th: in front of any existing html attribute? The answer is… pretty much! You can use th:id to assign a dynamic ID with the Thymeleaf + SpEL syntax, th:action inside of a

        tag. In fact, you can see the entire list of these values here.

        I'll mention here in passing that we have both an href and a th:href for the sake of Thymeleaf best practices… again, remember that the browser will ignore th:href when loaded outside of a web server, so if th:href is ignored, we have an href to fall back on. When this is run inside a web server context, the href will be ignored in favor of the th:href.

        Hopefully everything makes sense so far, but now let's get into the content within that special “at” syntax.

        Inside our th:href “at” syntax we have put in the following: /food-diaries/{foodDiaryId}(foodDiaryId=${foodDiary.id})

        This combines a plain old URL with the concept of a path variable (like in Spring). The difference is that we need to define our path variables right inside our th:href attribute (there aren't any annotations like in Spring).

        The syntax is fairly straight-forward, first you define a path variable by putting it in your URL with curly brackets (i.e. {foodDiaryId}).

        Note: you can add more than just one path variable in a URL, you'd just continue declaring path variables just like we did with {foodDiaryId} in the URL. You won't assign values to the path variables until the end of the URL.

        Once you're done with declaring path variables, then you'll need to assign values to them. This is accomplished by adding round brackets with an assignment statement: (foodDiaryId=${foodDiary.id}).

        We say foodDiaryId= because that's the name we used when we declared our path variable. Then we finish with ${foodDiary.id} using SpEL because that's how we can pull an actual value from the list of FoodDiary items that we're currently iterating over.

        Done and done.

        Using Multiple Path Variables in a Single Dynamic URL with Thymeleaf

        Just for the sake of completion again, here's a quick example of what it would look like to have more than one path variable defined in one URL:

        Dinner: Pizza

        The main thing to note here is that we don't actually start assigning values to our path variables until the end of the URL… and the assignment syntax is comma separated.

        Cool?

        Cool.

        Getting Iteration Details When Performing For Each Loop in Thymeleaf

        Switching gears now, let's close things off by talking about more advanced iteration techniques.

        Sometimes it's useful to have more information about the stuff you're iterating over.

        This could previously be accomplished in JSPs using the syntax… and thankfully, Thymeleaf has a way to get access to that exact same information.

        Bear with me again, the syntax is a bit different from the “c” tag library, but it's simple. Let's iterate over our FoodDiary items once more, but I want to get access to the iteration information:

        The code above will print out something like this:


        0 even
        1 odd
        2 even
        3 odd
        4 even
        5 odd

        So, the way to get access to the iteration information is just to add a comma after you declare the variable name for the iteration, and give your iteration status variable a name. I just happened to call it iterStatus, but you can call it whatever you like, it's just a variable name.

        Then once I've declared my iteration status variable, I can access it within the scope of my loop (in the case the scope is the div tag.

        There are some other properties that the iteration status variable holds. You can get the full list from the good folks at thymeleaf.

        The post EP05 – JSPs are extinct and Thymeleaf is the Culprit appeared first on Coders Campus.

        45 min
      5. EP04 – Spring Data and Why it Rocks (Part 3)

        Time to Create Custom Queries in Spring Data

        Hi again everyone,

        So, in our last post we talked about how to handle your standard CRUD operations with Spring Data's JpaRepository. It's a super easy way to handle all your basic CRUD needs.

        But what happens when we wander away from the “basic CRUD” operations, and we start to have a need for more customized queries outside of the findAll() and findOne() scenarios?

        Well this is where we embark on the journey to creating custom queries using a handle annotation called @Query

        The @Query Annotation in Spring Data

        First off, we need to go back and grab some of our previous code where we defined our own repository… the FoodDiaryRepository.

        Here's what the FoodDiaryRepository looked like:

        public interface FoodDiaryRepository extends JpaRepository
        {
        // it can be empty inside if you want, or later, you can add any custom queries if the standard set of CRUD operations aren't enough.
        }

        Now like I mentioned above, this will give us access to the default CRUD functionality within the FoodDiaryRepository, so we'll need to dig a bit deeper if we want to get more from our repository.

        Let's assume that we also want to have a way to find all items based on the meal type (i.e. Give me all the entries that are for breakfast, lunch, dinner or snack.

        That seems like it would be a reasonable thing to want. But it doesn't come as a query that we can run out of the box, so we'll need to create a custom query using the @Query annotation.

        Using @Query Without Writing any SQL/HQL

        Let's take a look at what our custom query would look like on its own.

        @Query
        public List findByMealType(String mealType);

        The beauty of using Spring Data is that you can get away with creating queries without actually having to write any queries.

        Sound confusing?

        Well it isn't… It just means that you can create SQL queries without having to write any actual SQL.

        You see, Spring Data uses clever conventions to create the queries for us based on how we name our methods in our repository interfaces.

        In my example above I started the name of the method with findBy. This signals Spring Data that I'd like to create a query with this method and that I'd like Spring Data to generate the SQL for me.

        Next, I give it the column (field) I'd like to find by… So in this case it's findByMealType.

        So, Spring Data will know to look for the mealType field inside of my FoodDiary entity.

        Lazy programmers rejoice!

        So what Spring Data will generate behind the scenes with our method is this:

        select * from food_diary where meal_type = ?

        Now, we're almost done here, but the last remaining thing to mention is that question mark.

        How does it know what to put in there?

        Well, don't forget that we declared our method with a parameter… Specifically a String mealType parameter.

        So this means that whenever this method is to be called, someone has to pass in a mealType that they'd like to “find by”.

        Okay, so now that I've explained what all that code does, let's take a look a the whole picture:

        public interface FoodDiaryRepository extends JpaRepository
        {
        @Query
        public List findByMealType(String mealType);
        }

        There's our repository in all its glory!

        Now whenever we'd like to query our database by meal type, all we need to do is call this new method and we'll receive a list of FoodDiary items that are filtered by the given meal type.

        Searching Between Ranges with @Query In Spring Data

        That's all well and good, but what about when we want to search for a range of data, for example: find all the meals that cost between $10 and $20?

        That's entirely possible with Spring Data too!

        Let's create some methods to handle these range type searches…

        @Query
        public List findByCostGreaterThan(Double cost);
        @Query
        public List findByCostLessThan(Double cost);
        @Query
        public List findByCostBetween(Double minCost, Double maxCost);

        The key here is that we combine what we already know about how Spring Data works with the “findBy” convention.

        So we tell Spring Data to “findByCost”, and then we add additional information to this query by appending “LessThan”, “GreaterThan” or “Between”.

        Let's put our queries into action.

        In order to do this in the simplest way possible, I've added some URL mappings to our RootController.

        Specifically, we'll add three different methods that handle the three new queries in our FoodDiaryRepository.

        Here's the code we'll add to our controller:

        @RequestMapping(value="/food-diaries/cost-less-than/{cost}", method=RequestMethod.GET)
        public String findByCostLessThan (@PathVariable Double cost, ModelMap model)
        {
        List findByMealType = foodDiaryRepository.findByCostLessThan(cost);
        model.put("foodDiaries", findByMealType);
        return "foodDiary";
        }
        @RequestMapping(value="/food-diaries/cost-greater-than/{cost}", method=RequestMethod.GET)
        public String findByCostGreaterThan (@PathVariable Double cost, ModelMap model)
        {
        List findByMealType = foodDiaryRepository.findByCostGreaterThan(cost);
        model.put("foodDiaries", findByMealType);
        return "foodDiary";
        }
        @RequestMapping(value="/food-diaries/cost-between/{minCost}-{maxCost}", method=RequestMethod.GET)
        public String findByCostBetween(@PathVariable Double minCost, @PathVariable Double maxCost, ModelMap model)
        {
        List findByMealType = foodDiaryRepository.findByCostBetween(minCost, maxCost);
        model.put("foodDiaries", findByMealType);
        return "foodDiary";
        }

        Okay, so what this new code means is that when we visit certain URLs, we'll trigger our new queries and get the appropriate results returned.

        So if we navigate to http://localhost:8080/food-diaries/cost-less-than/10 that means we'll essentially be running the following code: foodDiaryRepository.findByCostLessThan(10)

        Another example is if we visit http://localhost:8080/food-diaries/cost-between/10-15, this will execute the following method: foodDiaryRepository.findByCostBetween(10, 15)

        Note: in the real world, we likely wouldn't create URLs like we did for these queries. We'd most likely be taking input from an HTML page and passing that along via a different URL structure. But the purpose of this tutorial is to teach you about Spring Data, not proper ways to use MVC and URL structures.

        Using HQL with Spring Data

        Alright, so sometimes you just need to write your own queries.

        That's cool, I get it, we all want to be gangsta coders.

        Let's say that we're in a situation where we need to find out all the times we had pizza for lunch or something along those lines.

        Now, I'm pretty sure we'd be able to use the Spring Data method naming convention to create this query for us, but throw me a bone here, I can't think of any other queries to write off the top of my head that Spring Data doesn't already support.

        What would this look like?

        Well, we can actually pass in HQL as a String to the @Query annotation, like so:

        @Query("from FoodDiary where food = :foodParam and mealType = :mealTypeParam")
        public List findByFoodAndMealType(@Param("foodParam") String food, @Param("mealTypeParam") String mealType);

        There are a few things going on here.

        First thing to understand is that we needed to make use of parameters in our query. We used two to be exact, one for the food column called foodParam and another for the mealType column called meanTypeParam.

        This isn't unique to HQL, as using named parameters in our queries is just something that we need to do to make them function dynamically.

        What is slightly different is that we need to tell Spring Data how to map our method parameters to the HQL query params. To do this, we used the @Param annotation, which comes from Spring Data. With this, Spring Data is able to understand that the foodParam should map to the String food parameter (and same for the mealTypeParam).

        Outside of that, there isn't much else new or interesting going on here.

        Note: it doesn't matter what you name the actual method, as Spring Data will now ignore the method name in favor of the actual HQL query you specified in the @Query annotation.

        And finally, to wrap things up, here's the code I used to call our new findByFoodAndMealType method:

        @RequestMapping(value="/food-diaries/search/{food}-{mealType}", method=RequestMethod.GET)
        public String findByFoodAndMealType (@PathVariable String food, @PathVariable String mealType, ModelMap model)
        {
        List findByMealType = foodDiaryRepository.findByFoodAndMealType(food, mealType);
        model.put("foodDiaries", findByMealType);
        return "foodDiary";
        }
        Where to go from here?

        I've shown you a couple of the most common uses of Spring Data, but if you want to see even more examples, please check out the Spring Data JPA Reference Documentation.

        There you'll see examples like how to order your data, how to search while ignoring case, using distinct queries and more.

        Also, if you're curious to see how all this code we talked about today works, feel free to check out my GitHub page and peruse the code. Or feel free to clone this project via this URL: https://github.com/tp02ga/FoodDiary.git

        The post EP04 – Spring Data and Why it Rocks (Part 3) appeared first on Coders Campus.

        36 min
      6. EP03 – Spring Data and Why it rocks (Part 2)

        In the previous episode we talked about the first two letters in CRUD.

        So naturally that means that next up is the “U” in “CRUD”, we need to be able to update our existing methods.

        So, believe it or not, if you were playing around with the code that we wrote in the section above, you may have noticed that updating an existing record seems to work already.

        And you're absolutely right… it does work.

        So, your job is done!

        Shall we move on?

        Not yet.

        Let me first explain why it works…

        You see, when you used Spring Data to execute a findOne (or findAll) it will grab the id of the entity. We then put the entity on the model and passed it to our view.

        The view then passed that same Entity back to our server on POST, and therefore the id field will still be populated.

        When the id of an Entity has a value, Hibernate knows that that Entity must exist in the database, and therefore when you execute a save you probably want to update the existing record (and not add a new one).

        So you see, it's actually Hibernate doing the heavy lifting here. Because that id is already populated with a value, Hibernate will update the record with all the data you passed in.

        Sweet deal!

        Now let's talk “D”, the “Delete” statement.

        Let's start with an easy example… our example.

        When deleting a row from the database that contains a simple object (like the FoodDiary object) then it's as simple as invoking the delete method on our repository and passing in the object we wish to delete.

        Let's code up a delete method, shall we? (We'll get into the more complex scenarios afterwards)

        @RequestMapping(value="food-diaries/{foodDiaryId}", method=RequestMethod.POST, params="action=delete")
        public String deleteFoodDiary(@PathVariable Long foodDiaryId)
        {
        // we always need to load our entity from the database before we perform a delete
        FoodDiary foodDiaryItem = foodDiaryRepository.findOne(foodDiaryId);
        foodDiaryRepository.delete(foodDiaryItem);
        return "foodDiary";
        }

        Pretty straight-forward stuff. Be sure to load your entity first, then pass the loaded entity into your delete method and you're all set.

        But what about the more complex scenario that I mentioned? What is this scenario?

        It's when you have relationships in your objects.

        I've spoken about relationships before.

        Let's add a relationship into our FoodDiary object, I want to add a relationship in such a way that the FoodDiary entity is the child in the relationship (as this will create the difficult deletion scenario).

        Let's assume that we also have User entities in our code… it doesn't have to be fancy to work:

        @Entity
        public class User
        {
        @Id @GeneratedValue
        private Long id;
        private String username;
        private String password;
        @OneToMany(mappedBy="user")
        private Set foodDiaries = new HashSet<>();
        // getters and setters
        }

        And we'll also need to update our FoodDiary Entity to reflect a bidirectional OneToMany relationship:

        @Entity
        public class FoodDiary
        {
        @Id
        @GeneratedValue
        private Long id;
        private String food;
        private String mealType;
        private Time timeOfDay;
        private Double cost;
        @ManyToOne
        private User user;
        // getters and setters
        }

        Voila, we've created a relationship between a User and a FoodDiary (where one User has access to many FoodDiary objects).

        Now, we can talk about our deleting dilemma!

        What happens when we want to delete a FoodDiary Entity now? If you give our current delete method a try, you'll notice that it runs through the code just fine, but hibernate doesn't actually execute the delete anymore.

        What the heck?

        The reason why it doesn't delete the FoodDiary entry is because it's a child entry to a parent (with a bidirectional relationship).

        In our Java object scenario here, when we invoked the delete, Hibernate looks and sees that we're trying to delete the child object, but the child object still exists in the context of the parent (and the child still points to the parent).

        So that means there's more work to do here. Let's modify our delete method given our new scenario.

        @RequestMapping(value="food-diaries/{foodDiaryId}", method=RequestMethod.POST, params="action=delete")
        public String deleteFoodDiary(@PathVariable Long foodDiaryId)
        {
        // we always need to load our entity from the database before we perform a delete
        FoodDiary foodDiaryItem = foodDiaryRepository.findOne(foodDiaryId);
        // Get the User entity that owns this FoodDiary entity
        User user = foodDiaryItem.getUser();
        if (user != null)
        {
        user.getFoodDiaries().remove(foodDiaryItem);
        }
        // now we need to remove the user from our foodDiaryItem;
        foodDiaryItem.setUser(null);
        foodDiaryRepository.delete(foodDiaryItem);
        return "redirect:/";
        }

        Now, when we execute our delete statement, Hibernate sees that this FoodDiary item has been removed from the parent User object, and this FoodDiary item also doesn't reference the parent anymore… so it will execute the appropriate delete statement and remove the desired FoodDiary row from our database.

        Phew!

        That's a fair bit of extra work just to do a delete… but Hibernate doesn't want to take chances “guessing” at what exactly you want to delete, so you need to be explicit with it.

        Pro Tip: If you enable cascades (in the @OneToMany mapping), performing a delete of a parent object (the User in this case) will delete the parent and all the children without having to do any extra coding… you just execute a delete and pass in the parent entity that you loaded with a findOne() call.

        Download my Code

        For all of you “keeners” out there, I've created a GitHub repository for this project.

        Here's a link to the files so you can check them out.

        Or if you prefer, here's the clone URL so you can download the whole thing: https://github.com/tp02ga/FoodDiary.git

        The post EP03 – Spring Data and Why it rocks (Part 2) appeared first on Coders Campus.

        31 min
      7. EP02 – Spring Data and Why it Rocks (Part 1)

        CRUD

        It stands for Create, Read, Update and Delete.

        We, as programmers do CRUD all day, every day. It's at the centre of any app in any language on any platform.

        Thankfully, the good folks at Spring.io realized that since our jobs revolve around CRUD, there's room to make our lives easier.

        They've gone and taken out all the boring work of writing the code to support CRUD operations.

        So much so, that you can write one line of code, and your application can do all the standard CRUD operations on an Entity of your choice.

        Note: an Entity is “code” for a database table. You can create Entities using JPA… You'll see some examples of this soon.

        Prerequisites for Spring Data

        In this article I'm going to assume you have already set up a Spring Boot app. If you haven't, be sure to check out this article on how to do just that.

        Once you've got a basic Spring Boot app created, here's how to modify your pom.xml file to “activate” Spring Data.



        org.springframework.boot
        spring-boot-starter-data-jpa


        Note: be sure to paste the above code inside of your tags

        Spring Data in Action

        Okay, first thing's first… We need to have an Entity to perform our CRUD on!

        An Entity is just a Java object that will represent a table in our database.

        So what do you feel like storing in a database?

        How about a diary of what you ate? Why the hell not?

        So what should our diary contain?

        * Food eaten (pizza, apple, cookie, etc)

        * Meal type (breakfast, lunch, dinner, snack)
        * Time of day (8am, 12pm, 8pm, etc)
        * Cost ($10, $5, free etc)

        Okay, now with this information we can not only track what we're eating, but we can also see where we're spending too much money as well! Neat.

        Let's create this Entity as a Java object.

        public class FoodDiary
        {
        private String food;
        private String mealType;
        private Time timeOfDay;
        private Double cost;
        // getters and setters
        }

        That's a standard Java object with all the appropriate instance variables (and getters and setters). But this code doesn't yet have any JPA to tell it how to map this Java object to a database table. So let's populate the code with some JPA.

        @Entity
        public class FoodDiary
        {
        @Id
        @GeneratedValue
        private Long id;
        private String food;
        private String mealType;
        private Time timeOfDay;
        private Double cost;
        // getters and setters
        }

        Pretty easy right?

        Okay, so now I can start talking about Spring Data.

        We want to be able to do our CRUD operations on this “FoodDiary” object.

        So to do this, we need to create a repository… Specifically we'll create an interface that extends a Spring Data object called JpaRepository.

        Let's have a look at this code.

        public interface FoodDiaryRepository extends JpaRepository
        {
        // it can be empty inside if you want, or later, you can add any custom queries if the standard set of CRUD operations aren't enough.
        }

        That's it.

        You've now created an object that you can use to perform CRUD operations on your FoodDiary.

        Note: you need to tell it which object you'll be performing the CRUD operations on, you see that in the area. The FoodDiary part is you telling Spring Data which Entity you'd like to interact with… The Lomg part is you telling Spring Data what the data type of the ID field is. We declared the FoodDiary's ID to be a Long.

        Putting it all together

        In order to make use of our new repository, we need to call it from a Service or Controller.

        Typically it's good form to call repositories from Services as opposed to Controllers, as you shouldn't be doing any business logic inside your Controllers. But for the purposes of this example, I'll be bad and call the repository from my Controller (don't hate me!).

        Let's assume we have some sort of a RootController that handles any requests coming into the app:

        @Controller
        public class RootController
        {
        @RequestMapping(value="", method=RequestMethod.GET)
        public String rootMapping (ModelMap model)
        {
        model.put("foodDiary", new FoodDiary());
        return "foodDiary";
        }
        }

        Okay, so with this Controller, we will be able to get access to a “foodDiary” view if we visit the root URL of our application.

        So let's code up this “foodDiary” view.

        I'll make it an HTML file (called foodDiary.html)

        Food Diary Page
        My Food Diary
        Food:
        Meal Type:
        Time of Day:
        Cost of Meal:

        Okay, so now that we've got a very simple view put together, let's take a look at how we can make use of our Spring Data repository.

        In our view, we have created a form that executes a POST when someone clicks on our submit button.

        Problem is, we haven't yet created a method that will accept a POST from our view… so we'll need to modify our RootController:

        public class RootController
        {
        @Autowired
        private FoodDiaryRepository foodDiaryRepository;
        @RequestMapping(value="", method=RequestMethod.GET)
        public String rootMapping (ModelMap model)
        {
        model.put("foodDiary", new FoodDiary());
        return "foodDiary";
        }
        @RequestMapping(value="", method=RequestMethod.POST)
        public String rootMappingPost(@ModelAttribute FoodDiary foodDiary, ModelMap model)
        {
        foodDiaryRepository.save(foodDiary);
        model.put("foodDiary", new FoodDiary());
        return "redirect:/";
        }
        }

        Now we're getting somewhere!

        As you can see, the code that relates to our Spring Data repository only takes up one line: foodDiaryRepository.save(foodDiary).

        This will insert a new row into our database… of course, the foodDiaryRepository wouldn't exist if we hadn't declared it using an @Autowired annotation, but the Spring framework makes that part easy with dependency injection (via @Autowired)

        Alright, so that covers the “C” of “CRUD”, what about all the rest of those letters?

        Why don't we tackle the “R”, let's see how we can use Spring Data to read existing data from our database.

        Thankfully, this is also dead simple.

        You see, by default we have access to two useful methods:

        1. findAll()
        2. findOne()
        3. The findAll() method does just what it sounds like it does… it finds ALL the rows in the table that relate to the Entity that you're interacting with.

          Which means, if we do a foodDiaryRepository.findAll(), it will return all the food diary rows.

          Note: it returns a List of Entities, so in our case it would return a List

          For the purposes of our code, I'd like to be more specific. I'd like to have our app return ONE row based on an ID that I give it.

          So if I give it ID=1, then I want it to return the row in the database table that has ID equal to 1. I'll use a URL to specify which ID I'd like to have returned.

          So for example, if I go to: localhost:8080/food-diaries/1 I want it to return a row in the food_diary table with ID=1… or if I go to localhost:8080/food-diaries/34 it will return the row in food_diary where id=34.

          Make sense?

          Okay, so to accomplish this, we'll just need to add a new method in our controller:

          // this method would go inside of our RootController.java class
          @RequestMapping(value="food-diaries/{foodDiaryId}", method=RequestMethod.GET)
          public String getFoodDiaryItem (@PathVariable Long foodDiaryId, ModelMap model)
          {
          FoodDiary foodDiaryItem = foodDiaryRepository.findOne(foodDiaryId);
          model.put("foodDiary", foodDiaryItem);
          return "foodDiary";
          }

          What this new method does is that it will turn any number in the URL into a variable (known as a Path Variable), then use that path variable to query our database via the foodDiaryRepository.findOne() method.

          We then populate the model (our “foodDiary” entry) with the row we grabbed from the database. This, in turn, will populate our view with all the data from the database!

          Neat.

          Okay, so we're all set with the “CR” of the “CRUD”… in the next lesson/podcast episode we'll dive into how to do updates and deletes. Stay tuned.

          The post EP02 – Spring Data and Why it Rocks (Part 1) appeared first on Coders Campus.

          42 min
        4. EP01 – Spring Boot and Why it Rocks

          Possibly one of the greatest things to happen to Java (in recent history) has been the introduction of the projects from the wonderful people at Spring.io

          The Spring team seem hell-bent on making our lives as Java programmers easier and easier.

          I wanted to take a few moments to “tip my hat” to them with a few posts on the Spring projects I use and love the most.

          The first project on deck is Spring Boot.

          What is Spring Boot?

          Ever dreaded the thought of having to set up / configure a brand new Java application (or web application)?

          I have. Starting a new Java web project from scratch used to take me hours of work!

          Finding the right MySQL DB connectors, making sure to include all the necessary Maven artifacts, creating the right folder structure. Web.xml, context.xml and application properties.

          Hours and hours. Just to get to a point where I can make the project say “Hello World” when I visit the appropriate URL.

          Spring Boot fixes this pain.

          The best way to think about Spring Boot is that the smart ladies and gentlemen on the Spring team have hand picked the most commonly used libraries and put them together in such a manner that they work out of the box with sensible default settings pre-configured for us.

          With Spring boot, you can just tell it that you want to create a web app, with JPA and a MySQL database. Then copy in the properties that tell it how to connect to that database and you're ready to rock.

          I've timed myself… I can create an entire web app with a controller that integrates with a database and performs create and read commands… In 5 minutes.

          So that's an entire web application, with database integration, from scratch, in 5 minutes.

          And the only “code generation” is only class that has about 4 lines of code in it. This isn't like the Spring ROO days where you'd have hundreds of confusing lines of code created that made maintaining the thing a bit unwieldy.

          I'm talking, dead simple, straightforward code… 5 minutes.

          It's a bit of a game changer in my opinion.

          Now we can quickly create web apps from scratch and potentially launch them via the cloud in under an hour. How much would that impress a potential client?

          How to use Spring Boot

          Okay, okay, you get it. Spring Boot is awesome… So how do you use it?

          You have two options:

          • Using the Spring Tool Suite IDE to crate a new “Spring Starter Project”
          • Using the Spring Initializr website to generate a ZIP file
          • Note: Using the Spring Tool Suite IDE to create a “spring starter project” just saves you the small effort of importing the zip file and creating a project.

            Either way you choose, you'll need to tell Spring Boot which “dependencies” you'd like to add to your new project.

            By “dependencies” I mean that you need to tell Spring Boot if you'd like to include the libraries to support a web application… or if you'd like to use a MySQL database, or if you'll be using a templating framework (like Thymeleaf), etc.

            My most commonly used libraries to include are as follows:

            • Web (which includes all the Spring Framework stuff)
            • MySQL
            • JPA (which includes Spring Data)
            • Thymeleaf (which allows you to create and use HTML files instead of JSPs)
            • Spring Security
            • In this post, I'm going to use the first 4 of the 5 dependencies above.

              That means that we're going to create a web application built with the Spring framework + MVC, that's integrated with a MySQL database and uses JPA (Hibernate) with Spring Data. All brought together with Thymeleaf for our “views” (i.e. HTML files instead of JSPs).

              In other words, we're going to build a full-stack web application with Java.

              The Nitty Gritty

              So, the first step is to create your Spring Boot project.

              I'll show you the “universal” way of doing it via the Spring Initializr.

              1. Head over to start.spring.io
              2. Give your project a Group and Artifact name
              3. Search for and add dependencies
              4. Generate your project
              5. Once you've completed the steps above, you'll have a ZIP file that you can import into your IDE of choice.

                After impoting the project, you'll want to set up some properties to get everything primed and ready to rock.

                Here's a sample of the properties that I use:


                spring.datasource.url = jdbc:mysql://localhost:3306/
                spring.datasource.driverClassName = com.mysql.jdbc.Driver
                spring.datasource.username=example_user
                spring.datasource.password=password123

                spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect

                spring.jpa.show-sql=true
                spring.jpa.hibernate.ddl-auto=update

                spring.thymeleaf.cache=false

                 

                These properties are grouped by their use.

                The first four properties tell Spring Boot how to connect to your MySQL database… You'll need to be sure to create a blank database that can be accessed by your computer. That is outside the scope of this tutorial, but I have taught this subject before and you can watch a tutorial here.

                The second set of properties tell Spring Boot how you'd like JPA / Hibernate to Behave.

                The last property is to tell Thymeleaf not to cache our HTML pages (caching is good for performance, but in a DEV environment it's annoying as you'll need to reboot your web server every time you make a change to your HTML files).

                Okay, great… so you're at the point where you can fire up your new Spring Boot project in your web server.

                To do this in the Spring Tool Suite IDE:

                1. Right click on the project
                2. Hover over “Run As”
                3. Click on “Spring Boot App”
                4. If you don't see the “Spring Boot App” option (or the “Run As” option), you're either not using the Spring Tool Suite IDE, or you're not right clicking on the project folder in the IDE.

                  You should now see that your application boots up successfully! If it doesn't, the most common errors are that it can't connect to your database, so if you're struggling with that, maybe check other projects you've done where you successfully connected to your database in the past and see if you can spot any errors in your configuration.

                  Tips & Tricks
                  • Since we're using Thymeleaf for this project, you'll need to create plain old HTML files in the “templates” directory that got automatically created under the “src/main/resources” folder.
                  • Your javascript and css files should go in the “static” folder in “src/main/resources”
                  • You don't need to create an applicationContext.xml or a web.xml file, they're automatically created behind the scenes with sensible defaults in Spring Boot (you can always create your own if you like, it should override Spring Boot's versions)
                  • The post EP01 – Spring Boot and Why it Rocks appeared first on Coders Campus.

                    44 min

                  About Coders Campus Podcast

                  From the publisher's feed

                  Learn how to program using the Java programming language. This podcast will teach you step by step how to use the Java programming language to create your own applications or web applications! These…