Spring Boot Fundamentals: Connecting to Database | ChargeAhead LLC | Skillshare

Playback Speed


  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x

Spring Boot Fundamentals: Connecting to Database

teacher avatar ChargeAhead LLC, Technologist

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

12 Lessons (36m)
    • 1. Course Overview

      2:21
    • 2. Roadmap

      4:45
    • 3. Audience

      0:17
    • 4. Prerequisites

      0:23
    • 5. Tools

      1:11
    • 6. Demo: App Preview

      1:41
    • 7. Demo: Integrating with H2 database

      1:56
    • 8. Demo: Schema Initialization and Connection Pooling

      6:10
    • 9. Demo: Implementing CRUD operations

      4:47
    • 10. Demo: Adding Thymeleaf pages for adding/updating and deleting items

      8:55
    • 11. Demo: Switching to MySQL database

      2:36
    • 12. Summary

      1:01
  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels
  • Beg/Int level
  • Int/Adv level

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.

91

Students

--

Projects

About This Class

Connecting to a backend database is an essential part of any application in order to persist data. Spring Boot and Spring framework makes this extremely easy and efficient.

In this course we will continue building our Spring MVC app we started building in the course Spring Boot Fundamentals: Creating a Spring MVC app and connect it to a backend database using  Spring Data JPA’s repositories.

we will first use H2, an open-source in-memory database as a backend store.We will show how we can make Spring Boot load starter sql scripts to create our tables, insert data upon startup, which is useful when testing or prototyping.We will add the repository layer to our app to implement CRUD operations and we will see how Spring data JPA makes it so easy.

We will add thymeleaf pages for adding / deleting and updating inventory

Next we will switch the backend database to be Mysql. We will show how easy it is to switch to MySQL with literally changing a few properties and requiring no code change at all.We will also take a look at connection pooling along the way.

Meet Your Teacher

Teacher Profile Image

ChargeAhead LLC

Technologist

Teacher

Class Ratings

Expectations Met?
  • Exceeded!
    0%
  • Yes
    0%
  • Somewhat
    0%
  • Not really
    0%
Reviews Archive

In October 2018, we updated our review system to improve the way we collect feedback. Below are the reviews written before that update.

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.

Transcripts

1. Course Overview: connecting to him back in database is an essential part off any application in order to persist data. Spring boot and spring framework makes this extremely easy and efficient. Hello, my name is Bunker Jane, and welcome to the scores on Springboard Fundamentals. Connecting to a database in this court will first talk about who would be the audience for the scores. Pretty, because it's for them to get the most out of the scores and tools needed to follow along. You will continue building our spring Embassy AB. We started building in the course Springwood Fundamentals, creating a spring NBC app, and we will connect it to a back end database using spring Gator GOP repositories. Well, first use H two and open source in memory database as a back in store. It is a very small footprint and is easy to get started of it. Spring boot cannot to configure each to each SQL and double databases by only including the bill dependency that is pretty awesome. We will show how you can make spring Boot Lord Starter sequel scripts to create our tables , insert dude up on startup, which is useful when testing or further typing well and the deposit related to our app to implement Kurt operations. And we will see how Springdale a GP A, makes it so easy. We will and time leave pages for adding, deleting and updating infantry in production. It would most likely use the database like my sequel or Oracle or mongo db etcetera. So next we will switch the back end database to be my sequel. We will show how easy it is to switch to my sequel with literally changing a few properties and requiring no Court Jane at all. We will also take a look at connection pooling along the way. This is how our application would look after the scores. So now on application is connected to a back under the base from where it is fetching the list of items. We have also added the edit button, using which you can change the item attributes. There is also an R new item button using which you can add new items, and then there is a delete button using which you can delete night. Um, and all these crowd operations are happening against the backend database, so this would be an exciting course. Let's get started 2. Roadmap: I plan to create a series of courses covering the various aspects Offspring boot and wanted to take a moment to go where the courts roadmap to let him know what is coming and what we will cover in each course. The full scores, springboard fundamentals, basics and getting started. We will introduce spring boot, cover its fundamental concepts, and we'll get started developing applications. We will see how to use spring initialize er rapidly build and run a simple Weber first and then a console application in the next course spring. Good fundamentals Creating a spring embassy app will build a fully functional spring, NBC App for Managing Item Elementary. We will implement the model service controller and view layers to show the items in wintry really use timely for the view layer. We will explain how to integrate third body libraries like Jake Witty, bootstrap, acceptable in our application and refer good model attributes in the view Earlier will also introduce Springboard Death Tools, which makes development investing easy in the next course springboard fundamentals. Connecting to read a base will continue building over AB and corrected toe a back end database using Springer the GP repositories. We'll start with anonymity, database H two and then later switched to my sequel to show how springboard makes it easy to work with religious databases and switch them at ease will create the ad update, delete operations and complete our spring Embassy AB. Creating timely views for adding in the leading along the way will further explore time. Leave template engine In the next course. Springboard fundamentals. Building and consuming arrest based Web services will demonstrate how spring boot makes it easy to create and consume rest services. We will create great dressed endpoints for the items in that invent tree. We'll then see how to consume rest FBI's In our springboard project. We will take the Web layer off our spring remesy app built earlier, and it sort of fetching data from Madrid. Abi's will display the front end consume later from the rest FBI's In the next course Springboard fundamentals. Monitoring health and metrics with actuators will demonstrate springboard actuators. Detroit is a lot of useful health endpoints and metrics right out of the box with zero according, we will show how to expose and enable the health endpoints. We'll see how to implement our own custom health checks and create new endpoints in the course Springboard fundamentals. Improving performance by implementing cashing, we will demonstrate the cashing support. Springboard provides with just a dependency and a few annotations who can be wise and effective cashing strategy for the application. We will first demonstrate the cashing with the fourth cash manager Springwood provides, and the later sparked the provider to read this in the course Springboard fundamentals. Implementing security. We'll see how springboard makes it easy to implement security. Well first demonstrated basic authentication. Well, then switch over App to use Didem is authentication. Springboard actuator Security is now integrated with the main apse security. We'll see how to predict actuator endpoints. We want to talk about the or to support in the course spring. Good fundamentals are configuration with profiles and deployment. Using docker, we will see how to configure or app for different environments like Devon Prawer using spring for files. We'll also see Holder Doc arise our application docker containers provide consistent development, build test and production environments and make running and deploying our APS very easy. I would recommend taking these courses in order, but if your family, with a certain aspect of string boot. You must skip that course and more to the next one. Further, if you just want to take the course for a certain aspect, it should be self sufficient to explain the concept without necessarily having to take the previous ones, though I will always recommend great the previous courses for a better understanding. So following these cities, of course, is you would have a solid conceptual, and it's turning off. The various aspects of this framework rapidly start developing applications and micro services. All right, let's not talk about the audience for the scores. 3. Audience: This course would be useful for Java and spring developers who want to understand spring boot and also for sort for architects who want to understand this powerful free work and how they should apply to their applications. What are the prerequisites to be most successful with scores? 4. Prerequisites: there are not a whole lot of produces its for the scores. The only thing you need is some basic Java knowledge and some basic spring concepts. Even if you do not have a lot of family already with these, don't worry. I will try to explain the concepts along the way, and you should be able to follow along without much difficulty. Let's next talk about the tools you will need to follow this course. 5. Tools: we will have a lot of demos in the scores as a believe that is the best way to learn the tools I would using. The scores are off course. Jama. I would be using open Judy Kay Warren, 11 but you can feel free to use Java or open Judy Kay versions eight or above, and most of examples should work for the i. D. E. I would be using Sprinkle Sweet, which is a flavor of eclipse but is highly customized and optimized for spring development . I would be using the version for it is open source and free and comes with a lot of bells and whistles. But I think you would like, however, if your family with and we like to use some other I d like intelligent etcetera, please feel free to do so. We will use spring boot version 2.1 point four for the databases. We will be using H two and open source and limited a vase and also my sequel words in 8.0 point 15 You can find the gold for the demos in the scores and the falling good Have you are 6. Demo: App Preview: before we start, let me give a quick refresher of the app we had built in the course spring Good fundamentals creating a spring embassy app. This is a spring embassy app for managing item and wintry. So here we have packages for the model service and controller layers under our main package , where we have our main class. In the model layer, we have the items object with fields like Ida, Mighty item name, item price and Adam quantity. Then we have this service layer where we have just implemented a single get all mentored which returns a heart ordered list off items in this course will modify it to fetch the list from a back end database instead. Here is the controller package where we have items controller which we have mapped toe, then wintry path. Then we have mapped the slash all and slash on the right to refer to the get all matured with simply calls to get all matter from the service class acts of the model the items fetched and then heading and then returns the name of the time Leave you items view the time leave. Templates are kept under source main resources template where we have the items for you template but uses time leaf named space to retrieve the model attributes and display them in the tabular structure. We're referencing bootstrap for styling Our webpage going to the browser if it type http local host 80 80 slash and one tree We see her app as it looks. Now let's start connecting it to the database in the back end. 7. Demo: Integrating with H2 database: in this demo will add the issue database and splendid Aja Pierre dependencies to our poem file. And then we were configured our application properties file to point it to the Eastern database, as I had mentioned before, adding issue database should be fairly simple, just adding a dependency with spring boot doing all the order configuration. So here is our app. There is Go to the bomb file and on the dependencies for each two and spring boot started a GP a Detroit spring repository. Support for GP A. It uses hibernate. Now. If you were starting a new project, the H two, and sprinted a GOP dependencies can be added using spring initialize It also let's right, click on the project Jews, mirin and then update project. Now let's go to our application or properties file. Easter Database provides a very based console to look at the tables, created him etcetera to nimble that that is, add spring, not age to that console, not enabled equal to true, further by the Fort Age to store the data in memory. But let's make it persists to have filed, and to do that, we will add the property, spend our data source. Guttural equal toe Jerry BC cool and H to call and file colon slash home slash parables slash documents slash dogs slash dev hyphen D b So so. The name of our data file here is deaf half NDB, but you can give it any file Amy want. They're specify the Eastwood reverie. Want to use as Spring daughter the source. Don't revert. Last name. Equal Tow ork. Don't East Tudor driver. All right, that is it for H two. All right, now let's see how we can have spring boot initialize over scheme upon startup. 8. Demo: Schema Initialization and Connection Pooling: In this demo, we will see how, using spring boot and started Sequels, we can initialize over schema and insert data into our tables upon our application startup . We will also configure the connection pulling parameters for an application. It also modify our martyr object to become a chippy entity. Now we can create the table on their own and insert initial. Did I wondered if we need to? That would be the approach I would take for a production to the base. But for our demo purpose, we can have spring boot clear the table for us and optionally. We can also provide a script for it to insert did and the table for us. So let me add spring georgie ph dot hibernate dodea hyphen auto and give it a value create which first drops the tables if they exist and then creates them. We can all support here, create haven't dropped where it'll created upon start up and drop the tables when Decision factory is closed explicitly. Typically, when the application has stopped, the other values are update validate and none. When using update, it will compare the object model created based on the map ings with the existing schema and then hibernate updates the scheme according to the differences. It never deluded the existing tables or columns, even if they are no more required by the application. Relative tries to relegate the readable schema according to the entities that have created in the application and throws an ITER if the schemer doesn't match the energy specifications. Spring Boot chooses a deformed value for you, based on whether things of databases embedded, it defaults to create heaven drop. If no schema manager has been predicted or none of the wise and embedded database is predicted by looking at the connection, Type H s School DB each too and Derby are embedded and others are not. Tow it and seeing what's going on, let's also add a few more properties. Spender GOP a DOT show Heaven sequel equals True to Show sequel being executed by Hibernate Spring Georgie pH or properties, not hibernated brought format on discourse equally. Call the true before one. The sequel for us long that level got or not hibernate dot type Eagle to trace turns logging time for harmony to trace. By the way, Springboard Starter also has the logging dependency included and pulled in law. Reuters, like a cell a four J etcetera and auto configures it for us, so turn on logging for a certain package. It just putting the long, dark level but package name and the log level we want in forewarn error trace extra. You do not have to configure logging explicitly. Isn't that easy now The uncertain initial data. Let's create a file under swordsman resources and name it as important sequel When Spring Boots sees a file with this name and in the spring or GP a don't hibernate dot de deal Hyphen Auto is said to create or create drop. It will clear the tables and also execute this file. Inside this file, I have a couple of simple inserts to our table. All right. Now let's go to our model object items and converted to be a GP entity. We have to first market as an entity so that it can be poor sister to the database using G p A. We also need to designate a field as a primary key with the ad idea. In addition, typically, for the Primerica generation strategy, we used the are generated value In addition, fixed the imports. We can use generation type as auto to indicate that the persistence provider should begin appropriate strategy for the particular database auras identity To indicate that the poor resistance provider must assigned primary keys for the entity using a grid abuse Identity column, we can use the database sequence for the primary key generation specifying the sequence Name with the coalition. Type as stable indicate that the persistence provider must assign primary keys for the entity using an online database table to ensure uniqueness. Let me choose generation type as under the over here Spring boot, starting with version two users. Hickory CP for connection pooling Insert of this Tomcat GBC Connection pool It used with version one. Hickory CP has remarkable performance and enterprise ready features. It was included automatically as apart off the started and GOP a dependency which Poland started it gradually. BC dependency that is. Go to our application or properties file and let me based here some properties to configure connection pooling. You can configure a lot of properties like like minimum marital instances. Maximum pool size, idle time out in milliseconds. Full name Maxim Lifetime Gonna die Martin Milliseconds etcetera. So it's what he used to specify them. All right, let's don't start over, amp look it over console and we can see happen in our ports like drop table if it exists. And then the devil creates treatment based on the back into the base, and then it runs her script and inserts data. Let's go to the each to console, which is exposed at our base. Your URL followed by age to happen console here in the GBC girl. I have the girl we had on a properties file to point it to our file before using Name is S A with no passport. Let's connect. And here we see its console hair is or item stable, that is Cilic. Start from items and run and here with your data. So this is a good way for us to verify that everything is working well in our application. Next, let's wide our APP to use the database and implement decreed operations 9. Demo: Implementing CRUD operations: in this demo will make changes to our application to wider it up with the back end database . We will create a repository interfacing, which, as you will see almost no lines off court will generate a crowd matters for us. Then we will move on to our service class and remove the hard coded atoms list. We were turning back earlier and instead Fetchit from under the base. We'll also an traditional methods for the remaining crowd operations. So here's our application. Let's move on to create a repository interface. First, let's create a package for it. So right click and choose new package. Call it Conrad example for damage or repository, right click and choose New in the Face College items depository into fees. Market is a repository for spring scanning. Let's make it extend credit repository. Fix the imports, which takes in the object name and its primary key type. So items and interfere in our case. This is all we need to do for generating the crowd operations. This interface removes the need to write boilerplate code for insert update, delete select all SEC primary key operations. We can easily add more methods by following a simple convention. For example, to find the item name, we can write a method you're turning a list of items would find by and then the attributes , but making the first letter in uppercase item name bossing in string Item name Stringent GP able automatically take care off implementation details for us, we can add more search conditions toward like, using and and our operations like find my item name and at M price, for example, bossing in a second parameter as double item price. We can put standard terms like ignore case and we can are at the end underway clause. So we can, for instance, right a mid third returning a list of items find by item price order by item name which takes in double item price parameter. Let's now move on to the service layer. First thing we need to do is not a wire or items repository object. Next, let's remove the hardcore did a realist and instead the turn I d are not find all here. You can see the other matters with the repository interface automatically generates for us find by I d save delete all. And here are over custom mentors Springer the GOP A takes care of implementation details since find all mattered returns and the dribble list. Let's cast it as a list of items. Let us now create a method which returns optional items. Nimet is Get with Dixon. The item ideas a parameter it returns. I'd, er, find my i d taking in the item I d fix the imports. Next, Let's clear the matter for insert and update. We should have done the item created Automated. It takes in the new item to create or an existing item to update and then we call return Ideon don't save with takes in the item and it loved it. The item, if it exists or else will inserted. Finally, there is created elite matter to complete overcrowd operations. It takes in the item to delete, and then we call Ideon or delete. It sticks in the item to delete, so it's pretty easy to create the current implementations. Next, let's go to the controller over. Get all methods, stays the same. Let's just of everything is working properly so that start or app go to the Earl issued a p local host, a deity slash and wintry slash all Oh, we encounter an error that were missing before constructor for our entity. Let's go and fix that. Let me add a Newark's default constructor for our items. Object. Go to the girl and we see the two items. But this time our APP is pulling it all the way back from the red. A vase with all the layers in between working fine, Cool in the next demo that's anti controller and webpage for the Dominion current operations. 10. Demo: Adding Thymeleaf pages for adding/updating and deleting items: in this demo will and remaining current operations tower controller. We will create a webpage for the add and edit operations as well as create a button for the delete operation. Let's get started. First of all, let's go to our controller toe and a request mapping for a reading an item. So let us add Atra grist mapping with the Ural being slash and it slash the item i D, which has to be editor as apart parameter. We create a method public string and it where with the AK Party variable innovation, we say the i d in the path is integer and will be referred to as I d parameter. We also have the immortal attributes. Next we first opt in the item using ideas. Don't get I. D. Richard returns an optional item with an ad this item to our model as an attribute with the name item. You put the heading attributes this time as edit item with then return a newbie. You ended view for us to be able to edit the item fixed the imports. All right, let's create the edit view now for that. Let's copier items view dot html and based it with the name as edit view. As we're referencing in our controller, we've owned the sections with oversee, assists and Jalisco preferences. Let's remove the devil. It's Gmail. Let's create a form dark first, using th object, let us link it to the item. Attribute were passed in. The model relieves the bootstrap classes to style over form. Typically, you would have an underclass, which will be container or continual fluid condemning fluid goers. Entire Werth inside you would have a row or form rows. Each row can be divided in 12 columns. You can then use bootstrap classes to choose the columns you want for each control. If you Google bootstrap bread sizes, you would have classes to indicate excess for extra small devices like phones s him for small devices like tablets MD. For this stops and large for large devices. So, for example, we can divide the full throw into sections Eat section being six columns wide. The second row again weaken divided into sections, the fools one being four columns wide, and the next 18 columns the third row. We have divided in three sections, each four columns wide, so you get the idea this provides the flexibility to divide a row in the number of sections we want back to our page. Let's was creator Dave with the class formed a pro, we've only item I need to be hidden. So before that, however, Dave, insider with class call a 7 12 to all combined Entire. Oh, we made the import type hidden class as form control Name as item I. D is using this name that time ive links it to the I trim attributes in our model object wasn t it cool and field We bind it to our moral items at a mighty field it is a two were binding letting with based the next your hair the only difference here that we have first of fee two columns wide for the level bootstrap class, call hyphen form haven't level and then the text in port for our item name as item name required. The placeholder item name and linking it toe items or item name using th fleet letting paste for the remaining two feels item price on Adam quantity. Next, we need to add a button to write in view page 200 an item and call this page. So let's go to our atoms view page. Let me add another column, which is a hyperlink. But using the bootstrap Barton class, it will appear as a button. Isn't th h ref we call a u R L Notice for time Leaf Syntex. We need to put art science and then the ural slash country Slash 100 then But I don't variable inside curly braces. And then we passed the value of the part item using dollar items dot item i d. The rule is button, that's call it at it. All right, Let's see now how our page looks good. We see the edit link, Let's click it. And here we see that interview where we see the atom details. So the time leave bindings are working well, we need to add the summit button. Let us go back to read View page at a summit button. Now, using time leaves th colon action that has defined the post action as the girl with art in wintry slash update. We have not define a request mapping for it yet, so that's good for controller. On a request mapping for slash update, the matter returned the string and digs in the model and also the items item. Richards. The summited item from the form we first called the idea started great matured passing in the item drop dated. Next we get the list off all items at this point with the average values calling ideas not get all added to the model as a tribute items and the hitting back as item inventory. Then we don't redirect to slash country slash all. The redirect will help to prevent double submissions, and the Ural on the top will stay the same. That's distant. Now. When we click addict, we see the page. Let us change the quantity Say save and it comes back to the item's page with our change Nice Now there sport. Similarly, the link for ARD So let's go to the item view page. Let me put a hyperlink again. Using the bootstrap class, make it look like a button using th Golan a giraffe link. Link it to slash and wintry slash al euro For the text as Agnew item, let us don't define theatric West mapping for slash ariga role. Go to our controller, but at request mapping slash Add the method done the string and takes in the moral attributes. Here we initialize a new item added to the model on the heading as at item and again return edit view just that we're using the same view to read it as well. Azad of a repository of great method, will both insert or update. Let's go back to her form. We see the link. Let me add a new item, Click Save and here received in the list. Let's go to the age to console. Let us in on the query again and we see the new uncertain hair. Great. Now let us are the delete link. So let's go back to Adam. Your page. Let's copy the 100 Link Basic Under Tzur Older delete. Make the text as delete. They're just defined the job a strip on play action as it or don't conform. Are you sure? So the user says yes. Then it will involve the diligent Carol. Let us define it in our controller next, so that has defined the at request mapping for delete. Samos entered with a path variable inside that has got the item first, and then call ideas or delete, since ideas not get returns an optional item to get its value. We have invoked I don't get Met heard. Next. Let's call the ideas. Don't get all to get a list of whole items after the changes added to the model and heading and again Return related. Colon Slash and Wintry Slash all. Let's distant. It's on the main page. Let's click delete hair. Then it calls the deleted Huaral. The little item and rid of the current list of items back to us now is to is great for quick set of and testing. We're for production. Let's say we were using a my secret database. Let us see how easy it is to switch over AB. Now look at a MySQL database. 11. Demo: Switching to MySQL database: in this demo, you will see how easy it is to switch to a my secret database. For the purpose of this demo, we will again do two debates initialization using spring boot where it will clear the table for us as well is insert some sample data. It was January properties to look at my sequel here on my window. The next machine. I have a local instance of my secret of its running. It is very easy to download my sequel for your platform and get started. What? You can get your using a docker image in order to switch over AB to look at the data base, let me go to the application or properties fight. Comment out the east two properties using spring Or did the source door driver having class name specified? The My Sickle driver Specify the spring dot Did a source guttural as GBC calling my sequel colon slash slash local host cooler 33 or six slash the DeMann database Question mark and specify the server Time zone is UTC. Finally, thus far, the user name and password there is go to our formed an XML file. Next, let me comment the Easter dependency and let's under dependency for the my sickle delicacy driver. That is it. The court stays the same. Let me start the APP and from the console you can see springboard issues the appropriate deal statement for creating tables and MySQL database and inserts the two rules for us there. Let's go to the browser and type http local host 80 80 slash in wintry slash all. And we see a list of her items that are another item by clicking. Add new item and save. We see the new item in the list Hair. Now they've been connected. The MySQL database using the command My sequel hyphen You user name as Deb User and having people Password. Let me enter the password. Let me show the statement. Select star from items and we see our new item in sorter. So our Abbas correctly wired and working with a MySQL database. And you saw How is it waas the switch it from each to my sequel. With this you have complete end of the scores. Let us summarize what we talked about 12. Summary: in this Gore's. We started off talking about the audience tools and prerequisites for the scores. We took the spring embassy app. We started a number course springboard Fundamentals fruiting a Spring Embassy app and linked it to an issue database in the back. And we saw how we can use the starter Sequels. But spring boot to routed Abbas's initial addition upon application startup, we saw how to specify connection pull properties. He was in Hickory CP with then implemented crowd operations fingered a GPS card repository interface. Does the implementation of the card matters for us? And we have to write no boilerplate code within added support for adding editing and deleting items in our view layer using time leaf. Finally, we sure how easy it is to switch your AB to use a MySQL database in the back end full of this course. Give you a good and it's turning off connecting your springwood app with the back end database. Thanks for watching