Feb 5, 2017

Spring Boot application with Spring Data JPA

In this blog We will build a small REST based service to manage users for a larger application with following Technology Stack

  • Windows 7
  • Spring Tool Suit (STS) IDE
  • MySQL DB
  • Spring Boot (1.5.1)

Create Project

Lets start with creating a Spring Boot project. Easiest way to create this project is go to Spring Initializer website. For this project we are generating artifacts with following

Group: com.techcielo.myapp
Artifact: usermanager

Also we will search and add following Dependencies
JPA, Web




Now click on Generate project and project will be downloaded on local machine. Extract and Import this project in your STS workspace.



STS will download required libraries and build the initial project. One all download is completed right click on project ==> Maven ==> Update Project. It will remove all dependency related issues and build you a clean Maven project with Spring Boot, Spring Data JPA and Hibernate dependencies.

Configurations

Since Spring Boot is still not aware of what DB we want to use this project, is yet to have any libraries/configuration related to MySQL so once the project is build we will create configuration file application.yml in src/resources folder and provide following MySQL configuration. (Spring Boot by default creates application.properties you may want to delete it)

application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 
    platform: mysql
    initialize: false
  jpa:
    database-platform: org.hibernate.dialect.MySQLDialect


We also edit pom.xml and add dependency for MySQL java connector.

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

We are yet to create services but before that we will create DB for our operations

CREATE TABLE IF NOT EXISTS `user_mst` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(50) NOT NULL,
  `last_name` varchar(50) NOT NULL,
  `is_active` tinyint(1) NOT NULL,
  PRIMARY KEY (`id`)
)

Create Java Classes

Now lets create Entity class for this table as follows.

And a repository to access this entity.

We also create a REST controller to  access this Business entity.

Run the project

Once these classes are created right click on Generated App class (in this case UsermanagerApplication.java) ==> Run As ==> Java application.
It will start inbuilt Tomcat server and make REST services available on port 8080. You can see certain REST urls in logs as shown below.

2017-02-04 20:54:36.422  INFO 9316 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/user/all],methods=[GET]}" onto public java.util.List<com.techcielo.myapp.bean.UserBean> com.techcielo.myapp.controller.UserController.getAllUsers()
2017-02-04 20:54:36.423  INFO 9316 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/user/],methods=[POST]}" onto public com.techcielo.myapp.bean.UserBean com.techcielo.myapp.controller.UserController.createUser(com.techcielo.myapp.bean.UserBean)
2017-02-04 20:54:36.425  INFO 9316 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-02-04 20:54:36.425  INFO 9316 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-02-04 20:54:36.454  INFO 9316 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-02-04 20:54:36.454  INFO 9316 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-02-04 20:54:36.497  INFO 9316 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-02-04 20:54:37.045  INFO 9316 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-02-04 20:54:37.489  INFO 9316 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-02-04 20:54:37.497  INFO 9316 --- [           main] c.t.myapp.UsermanagerApplication         : Started UsermanagerApplication in 22.065 seconds (JVM running for 27.429)

Test your application

Now first we create few users with POST requests using POSTMAN or RESTClient. I am using RestClient from Mozilla Firefox.

Set
Custom Header "Content-Type:application/json",
Method:POST
URL:http://localhost:8080/user/
Body: {"firstName":"Keyur","lastName":"Joshi","isActive":true}



Now send this request and you will get response as shown below.





Now send GET request by RestClient or use url in browser to check if POST call has successfully added User in DB or not.