In the last session we have learned everything about spring boot ,we have also created spring boot rest controller with basic CRUD operation. In this post we are going to learn about how to integrate spring boot application through data base.In this lesson we will be using spring data JPA to connect data source with spring boot application and flywayDB for data migration.
Identifying framework for Integration
To integration spring boot application with data source we need to understand how our persistence layer would work and what are frameworks needed to developed full functional spring boot application.Since we are talking about persistence we are going to focus on server side part of our spring boot application. Currently we have rest API set up for controller under spring MVC framework and this sits at our top of server side stack.
We are going to use spring data JPA to connect to data source and embedded H2 data base for persistence layer.To integrate spring data JPA we just have to add spring boot data JPA starter in pom.xml and spring boot auto configure all the dependency needed for spring data JPA. Spring boot data JPA is an ORM framework used in spring which is build on top of Java persistence API.We will also learn how easy it is to integrate any third party framework by using spring boot.
Please open the last project and in pom.xml we are going to add couple of more dependency to make our persistence layer work.We will be adding two things here -
1. H2 Dependecy
2. Spring boot starter data JPA
Now go to the dependency hierarchy tab and have a look into that spring data JPA has added couple of dependency internally like spring JDBC.
Now go to application and start your server. Sometimes you get below exception while starting spring boot app.
If you get an exception like above it means spring boot is missing dependency for jaxb-api. To resolve this add the below dependency in pom.xml and run the application once again.
Next we are going to add couple of properties in application.properties file.
By adding logging.level to DEBUG you can see all logging information what spring boot does at application starts up.The other two properties is added for H2 database ,first one is to enable the console for H2 database and the second one is the path mentioned to opne h2 console.After start up open up
http://localhost:8181/h2" in any browser you can see now h2 console -
Spring boot has auto configure h2 data base for us with default set up ,click on the connect botton to connect to data base and you can see h2 console now.
In the real world application mostly other external data base like Oracle,postgres and MySql will be used than using embedded data base like H2.In that case data base would be installed in it's own server ,to connect to database through spring boot need to provide JDBC connection for it.So we have to provide data source into spring boot application.Besides setting up database connection info spring boot also tries automatically set up data source pooling for you.In an enterprise application having s strong connection pool can greatly improve your database throughput. Spring detects any common pooling library in your classpath and auto configure to integrate that pool and tied it with data source.Spring boot has tomcat-jdbc as default pooling strategy as it has pretty good performance and concurrency out of the box.You can also use other connection pooling library like DBCP.
Now that we are going to add below properties in application.properties file for datasource.
Here we have mentioned spring data source Url ,username ,password and the driver to connect spring boot application to h2 database.As of now keeping username and password default though you can change it.In datasource url I am keeping default name "test" you can change it to any convenient name that you prefer.Now start up your application and again go to database console.
To test the connectivity there are sample SQL script has been provided you can pick one and run on console and see if it run without fail.I am taking for creating Test table.
You can see that Test table has been created successfully.
As we include spring boot starter data JPA into pm.xml file ,spring boot internally download spring jdbc for database connection and tomcat-jdbc for database pooling and add that to classpath. By including pooling properties in application.properties file you can define pooling strategy.
Add below properties to define pooling strategy and start up your application.
Integrating FlywayDB
If you are not familiar with FlywayBD I can give you basic info ,it is used for database migration in application .In a large enterprise application there are tons of table involved initially.Creating those tables in database would be hectic job.FlywayDB has one time job to run the flyway script and it will do the job.
To integrate flywayDB in spring boot need to do following things-
- Add the flyway dependency
- Configure flyway datasource
- Create migration scripts
- Migrate on app start up
First add flywayDB dependency in pom.xml ,Next spring boot need to make sure that datasource is available for flyway.Once the app has the dependency in the datasource set up you can start creating migration script to create and modify data.
Next need to identify a place where migration script lives so that flyway can detect it.The location essentially lives on a classpath.I am going to create a new directory name db in source/main/resources folder under which create a migration folder.All the migration scripts resides here.Kindly follow below steps -
We also have to add below property in application.properties file-
The flyway.baseline-on-migrate property true tells the flyway that this is first time flyway that ever been run.This property make sure that flyway gets install and set up correctly.Since hibernate is running as entity manager
The other property added to tell hibernate entity manager for our JPA tier, it will try to auto create any entities using ddl of those entities.So this is kind of conflict what flyway is really trying to do.By making auto-ddl property false we shutting off the auto creation of entities and totally relying on flyway to create our database structure.Run on the application and login to the h2 console.
You can see now at the left hand that "PROMOTION" table has been created.
Spring Boot Java Configuration
If you have ever come across spring application then you must be knowing that in the spring application all the configuration is done in the xml file.In spring boot we don't have any xml file as such. Spring boot provide java configuration as an option to create any configuration. As most of configuration can be done in the application.properties file still you may need to do some configuration for your application that falls out of application properties file.This can be done by using @Configuration annotation in java class.Spring boot sets up configuration at application start up.
To demonstrate how @Configuration works let create a public class and with @Configuration at the top.
Let's create datasource for our application outside the application.properties file.To do so we would need to create a class PersistenceConfiguration and annotate it with @Configuration annotation.Inside the class we have to create public method annotated with @Bean annotation.At the application starts up this java configuration will be set in spring application context and can be access anywhere in the application using given public method as the method returns bean.
The @Bean annotation tells spring boot that return value of this method would be specifically stored as spring bean in spring context.
@ConfigurationProperties annotation tell the datasource builder to use datasource connection and pulling properties located in the application.properties file where the property begin with "spring.datasource" prefix.
Adding Spring Data JPA
So far we have discussed spring boot persistence layer and how it works.In this section I am going to demonstrate how do we use spring data JPA to create JPA entity and repository for spring data JPA.So that you can perform all the CRUD operation we have built in the last post can be done by using database through rest controller.In this section the focus would be on spring boot data JPA not in spring boot as spring boot concept have discussed already.Spring data JPA is a big topic in itself I am not covering into details as I will come up with another tutorial separately for spring data JPA.
As this post is a continuation of my previous post on spring boot fundamentals ,if you have gone through that I would recommend to go through that as we will be using the same application to demonstrate spring data JPA.
Open the Promotion class in the model package, to make this class as a JPA entity need to annotation this class with @Entity.
As JPA entity is mapped with database table we have to give the @Id annotation to map primary key for this entity.In JPA @GeneratedValue defines a strategy for generating primary key.In this case @GenerationType.AUTO increment primary key automatically.
Secondly we have to create Jpa repository to stored jpa entity.In spring data JPA the JPA repository by default define all CRUD operation which is going to perform on entity.
I have created an interface PromotionRepository which extends JpaRepository of generic type Promotion and Long.Here promotion is entity and Long is data type defined for primary key.
In the PromoController class modify as per given below-
Starts up the app and see if it started without any fail.You can notice that in controller we are auto wiring Jpa repository.Whenever you hit the controller now it will directly talk to database and all the CRUD operation would happen through database.
That's it!!! Congratulation you have learn how spring boot application talk to persistence layer.
Note :This post is continuation of Fundamentals Of Spring Boor.If you want to learn this post first you have to read the privioud one.
Kindly share your feedback if you really like this tutorial as will give me confidence to come up with more session to help you learn new technology..
I have covered Spring boot in multiple post, hence kindly follow below order to learn completely-
Comments
Post a Comment