Spring Boot with Visual Studio code (Visual Studio Code) Part 2

Tariqul Islam
11 min readFeb 4, 2019

--

Programmer are recommend to use spring boot frameworknormally spring boot recommend to use eclips or intellij idea as development environment. But I would like to use my favourite code editor visual studio code(Vscode) as development editor for spring boot. In my previous part of series, I discuss about how to configure the enviroment for java in visual studio code.if anyone interested for configuring the java development environment with visual studio code, read part 1 of the series.

  1. Java with Visual Studio code (Vscode) Part 1

Today, I will discuss about how to configure the spring boot with visual studio code and mysql database. Part of the dicussion include basic structure and features about spring boot jpa repository, service and controller.

Configure the Spring boot with Visual Studio Code

Before starting the project, we need to download pre-configured spring boot starter from start.spring.io web resource.

  1. Select the Maven Project from generate dropdown
  2. Then Select the Java as language
  3. Select the stable version of spring boot, I have selected 2.1.0

Before starting the project you need to know about basic project structures and some important syntax and topic of spring boot application.

POM stands for Project Object Model. It is the fundamental unit of work in Maven. It is an XML file that resides in the base directory of the project as pom.xml.

The POM contains information about the project and various configuration detail used by Maven to build the project(s).

All POM files require the project element and three mandatory fields: groupId, artifactId, version.

4. Type groupId from Group Text Box

This is an Id of project’s group. This groupId is unique in an organization or a project. For example, if the group of company has a bank related software, we can name it as com.company.bank, which has all bank related projects.

5. Type the artifactId from artifactId Text Box

This is an Id of the project. Generally it is used as name of the project. For example, if the bank has agent-banking sections, we can name it as agent-banking which is under comp.company.bank groupId.

6. Find project dependency from Dependencies . Add it to project

7. List of Dependency I have to add for this tutorial.

“web”, “mysql”, “jpa”, “security”, “Actuator” , “DevTool” and “Lombok” as Dependency.

Web --> Starter for building web application, including RESTful, Spring MVC. And Tomcat as the default embedded container.mysql --> JDBC Type driver for MySQLjpa --> Starter for using Spring Data JPA with Hibernatesecurity --> Starter for using Spring SecurityActuator --> Starter for using Spring Boot's Actuator which provides production ready features to help you monitor and manage your applicationDevTool --> additional set of tools that can make the application development experience a little more pleasantLombok --> Lombok is used to reduce boilerplate code for model/data objects, e.g., it can generate getters and setters for those object automatically by using Lombok annotations. The easiest way is to use the @Data annotation.

Configure and Open The project In visual studio code

Install the Spring boot Extentions Pack for getting Spring boot Development Environement and Intellisense to Visual Studio Code.

  1. Open the Application Folder which is generated from spring initiliazer website.
  2. It will automatically configure the Java Language server. Which will give the functionality to run and debug the spring boot application.

3. Install the Lombok Annotation from extentions from visual studion extension sections. and Reload the visual studio code.

1. Change the Main Class Name to Application.java from GraphqlSaterApplication.java

2. Create Four Folder or package named Controllers , models , repositories , services .

3. Controllers contains the Spring Boot’s Controller or RestController to create rest api service.

4. models contains the persistance objects or database tables's model which is then use for consume the data from database or datasource.

5. repositories , Get all Spring Data JPA and Hibernate class, which is persist data from models.

6. services , it will be use for consume the third party api services to spring boot appications. And Developer also build the own application services , which will be then available from service packages.

7. resources contains all the resources which will be used for this spring boot application, the resource could be message handling files, language files and application configuration file and static website which consume the spring boot rest services.

Configure Mysql Extensions to Visual Studio Code

Figure 2.1 Install MySQL extension to vscode to access mysql server and create database

(1) Mysql extension pack for visual studio code

(2) After Installation, you can find the toolbar at left side of visual studio. click on plus (+) button.

(3) Then Clicking the (+) icon, we must add Database Host Name. So, we need to add localhost in host entry. then click enter .

(4) Then add username of the mysql database and hit enter.

(5) After that Add the password , (6) then add port number.

(7) If you have ssl certificate to connect to mysql, add the path to it. if not press enter

(8) Click on Database server. Click right button , you will get create new sql command in context menu.

(9) Write the Query and Run Mysql Query , (10) you can see the output in console

(11) I have created test database named testapp .

Connect With Database for accessing the datasource

In resources folder, we need to add application.properties file for declaring application configurations, or database configurations.

To run an app with DataSource, all you need is the connection information and Pool-specific settings . In Line 1…9,shows how to define a JDBC data source by setting properties.

  1. spring.datasoruce.url used for taking url of jdbc connection. using useSSL false, avoid ssl connection for mysql database.
  2. spring.datasoruce.username and spring.datasoruce.password takes the mysql database username and password for accessing the data from mysql database

For the record, the spring.jpa.hibernate.ddl-auto property is used for passing the value to Hibernate property named hibernate.hbm2ddl.auto. It has a value create, create-drop, validate, and update . those value is using for running operation related to schema tool management which manipulate the database schema at startup.

spring.jpa.properties.hibernate.dialect Allows Hibernate to generate SQL optimized for a particular DBMS, I am using org.hibernate.dialect.Mysql5InnoDBDialect as value for optimized the sql using InnoDB database engine.

server.portspecifiy the server port number for embedded webserver tomcat.

Sample Project for discussing about Spring boot

I have created simple project which will help the developer understand how the spring boot application works with lombok . I have created the entity named member . And Expose the rest service and rest controller for that entity.

Create Model with lombok for spring boot application

In this project, I have to add entity class which persist object of the members table of database named Member in models folder in project.

In line 9@Data, is a annotation class for lombok project.It bundles the features of @ToString, @EqualsAndHashCode, @Getter / @Setter and @RequiredArgsConstructor together.In other word, it generates all the boilerplate that is normally associated with simple POJOs (Plain Old Java Objects) and beans.In line 10@Entity, simplifies Java persistence api(JPA). it provides an Object Relational Mapping approach to map java object to Relational Database Table. it will persist all the fields of relational database, except transient field.In line 11, @Table, This annotation specifies the primary table for the annotated entity.In line 14, @Id, Specifies database table primary key of an mapped entity.In line 15, @GeneratedValue, specification of generation strategies for the values of primary keys. it takes IDENTITY and AUTO as value.In line 16, @Column, Specifies database table mapped column for a persistent property or field.@GeneratedType, Defines the types of primary key generation strategies.In line 20, @NotEmpty, The annotated element must not be null nor empty. Supported types are: CharSequence, Collection, Map and ArrayIn line 27, @Email The string has to be a well-formed email address.

Create Repository for Spring Boot JPA(Java Persistance Api)

Spring Data JPA’s most compelling feature is the ability to create repository implementations automatically, in runtime from a repository interface. Spring Data JPA also allows you to define other query methods by simply declaring their method signature.

The goal of the Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores.

How does it works?

The central interface in the Spring Data repository abstraction is Repository. It takes the domain class to manage as well as the ID type of the domain class as type arguments. This interface acts primarily as a marker interface to capture the types to work with and to help you to discover interfaces that extend this one. The CrudRepository provides sophisticated CRUD functionality for the entity class that is being managed.

In line 4, save method will save the given entity, then returns the entity identified by the given ID.In line 6, return the entity by primarykeyIn line  8, return all entities of domain class.In line 10, return the number of entity saved in persistance store.In line 12, delete the given entity.In line 14, Indicates whether an entity with the given ID exists

JpaRepository extends from CrudRepository. CrudRepository interface has implementation of CRUD operation. If we do not need any customized or complex Query, Just extend the Crud interface, it will provide all the function related to CRUD operation. But in this project we need some costomized query, so we are using JpaRepository for expose repository for Member entitiy.

In line 9, we are using the custom Query method findByEmail . Now for project purpose we need to discuss how this Query method work in JpaRepository .

Query methods

Standard CRUD functionality repositories usually have queries on the underlying datastore. With Spring Data, declaring those queries becomes a part of Repository.

  1. Declare an interface extending Repository or one of its subinterfaces (CrudRepository, JpaRepository) and add domain class with ID type, which should handle repository, as shown in the following example:

interface MemberRepository extends JpaRepository<Member, Long> { … }

2. Declare query methods on the interface.

interface MemberRepository extends JpaRepository<Member, Long> {
List<Member> fineByEmail(String email);
}

Query Creation

The query builder mechanism built into Spring Data repository infrastructure is useful for building constraining queries over entities of the repository. The mechanism strips the prefixes find…By, read…By, query…By, count…By, and get…By from the method and starts parsing the rest of it.

In the prior example, I have defined a common base interface and add findByEmail Query methods, if the application use JPA, it matches the method signatures in CrudRepository. So theMemberRepository can find individual users by email.

Create Service in Spring boot for Expose the CRUD or other operation

Service Components are the class file which contains @Service annotation. These class files are used to write business logic in a different layer, separated from @RestController class file.

From line 12..13 I need to @Autowired the Member Repository . So what is @Autowired , you have this question in mind now?

In Spring 2.5, the framework introduced a new style of Dependency Injection driven by @Autowired Annotations. This annotation allows Spring to resolve and inject collaborating beans into your bean.Once annotation injection is enabled, autowiring can be used on properties, setters, and constructors

Optional Class is introduce in JAVA 8. the pupose of this class is to provide the top level solution for representing the optional value instead of null reference.

orElse API is used to retrieve the value wrapped inside an Optional instance. It takes one parameter which acts as a default value. With orElse, the wrapped value is returned if it is present and the argument given to orElse is returned if the wrapped value is absent.

In line 28, findById is a repository methods which return value is optional, it represent Optional class. so I have used orElse and pass null as value, so I can then check member object is available or not in database.

Add the Spring boot Rest Controller

@RestController is a specialized version of controller, which is used for creating Restful api with spring boot. It is a specialization of @Component and is autodetected through classpath scanning. It adds the @Controller and @ResponseBody annotations. It is typically used in combination with annotated handler methods based on the @RequestMapping annotation and It converts the response to JSON or XML and it does not work with the view technology, so the methods cannot return ModelAndView.

ResponseEntity represents the whole HTTP response: status code, headers, and body. Because of it, we can use it to fully configure the HTTP response. If we want to use it, we have to return it from the endpoint; Spring takes care of the rest. ResponseEntity is a generic type. As a result, we can use any type as the response body.

For Sample Project purpose,I have added MemberController REST Controller. That Controller provides access for client appication to perform CRUD operation through API.

@RequestBody annotation maps the HttpRequest body to a transfer or domain object, enabling automatic deserialization of the inbound HttpRequest body onto a Java object.

Form 17…20,create get http request endpoint to get all members from database using memberService.getAllMembers() service method.

From 22…25, create http post request api end point , which takes the Member object as response body ,using memberService.saveMember(member) service method to save member and return the member information in response by using ResponseEntity.ok() method.

From 27…31, create http put request end point, which takes the Member object as ResponseBody and member id as PathVariable to update member information by memberService.updateMember() service method.

From 33…45, create http delete request api end point, wich takes the id as PathVariable and using memberService.deleteMember() service method to delete member.

In this endpoint, I have to build the custom response body because, memberService.deleteMember() only return true or false. so i have to use Map collection, which contains the string as key value pair. And return the response Response.status(http status code).body(custom map object) chain function.

Testing API with Postman to Check the sample output

--

--

Tariqul Islam

Tariqul Islam have 9+ years of software development experience. He knows Python, Node Js and Java, C# , PHP.