Outcome and Goals

Why Spring Boot?

Why not use Spring directly?

What do we need?

pom.xml

java -version

java version "1.8.0_221" Java ( TM ) SE Runtime Environment ( build 1.8.0_221-b11 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 25.221-b11, mixed mode )

JAVA_HOME

echo $JAVA_HOME

/Library/Java/JavaVirtualMachines/jdk1.8.0_221.jdk/Contents/Home

Let’s start

Setting up pom.xml

pom.xml

parent

pom.xml

Setting up the entry point of the spring boot project.

src/main/java

SpringApplication.run(RestAPI.class, args);

Run

http://localhost:8080

Let’s add a controller

RestController

StatusController.java

io.singh1114.springboottut.status

RestController

RequestMapping

http://localhost:8080/status/

Return Data from the Controller

StandardController.java

Standard.java

io.singh1114.springboottut.standard

Standard.java

getter

setter

constructor

StandardController.java

GET

/standards

Spring Boot

JSON

Let’s think about data

School

Standard

Students

School

GET - /schools - Get all schools. GET - /school/id - Get info of the given school. POST - /school - Create new School. PUT - /school/id - Update info of the school. DELETE - /school/id - Delete the school.

Let’s add a persistence layer: Database

MySQL

Setting up MySQL

You can install MySQL using a simple brew command in MAC.

brew install mysql

sudo apt install mysql

Then you can start the MySQL server using the command.

brew services start mysql

Now you will have to create a database for the Spring Boot application to interact with.

mysql -u root --password

Once, you are inside the MySQL shell, you can create the database using this command.

create database springguide ;

Once you are done with database creation, you can add this content to the file src/main/resources/application.properties .

spring.datasource.url = jdbc:mysql://localhost:3306/springguide spring.datasource.username = root spring.datasource.password = <Your password> spring.jpa.hibernate.ddl-auto = update

Adding more dependencies

MySQL

Hibernate

pom.xml

... </dependency> <dependency> <groupId> org.springframework.boot </groupId> <artifactId> spring-boot-starter-data-jpa </artifactId> </dependency> <dependency> <groupId> mysql </groupId> <artifactId> mysql-connector-java </artifactId> </dependency> <dependency> ...

Build the school Model.

io.singh1114.springboottut.school/School.java

Java

javax.persistence

java: package javax.persistence does not exist

javax.persistence

<!-- https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api --> <dependency> <groupId> javax.persistence </groupId> <artifactId> javax.persistence-api </artifactId> <version> 2.2 </version> </dependency>

Entity

@Id @GeneratedValue ( strategy = GenerationType.AUTO ) @Column ( name = "id" )

Id

Primary key

GeneratedValue(strategy = GenerationType.AUTO)

Column

Let’s make the Db Access layer (Repository)

io.singh1114.springtut.school/SchoolRepository.java

package io.singh1114.springboottut.school ; import org.springframework.data.repository.CrudRepository ; public interface SchoolRepository extends CrudRepository<School, Long> { }

CrudRepository

<School, Long>

Controllers

Singleton

@Service

io.singh1114.springboottut.School/SchoolService.java

Controller

Integration testing of APIs in Spring-Boot( Java) with Junit | For Beginners #java #springboot #testing



October 18, 2019 7 mins read



Java is one of the most widely used programming languages in the world. Not only it is widely used, but it is also being used as the core part of the top software companies in the world. So, if your dream is to work for those top companies, you better know a little bit of Java. This tutorial will help you to create a CRUD(Create, Retrieve, Update and Delete) based application. In this tutorial, we will create every API for aAfter going through this guide, you will be able to build complex applications using Spring Boot framework. I would encourage you guys to create a small project of your own as well, as we move forward in this guide. During the course of the article this GitHub Repo will contain the code related to the changes being made.While building a web application, the main goal of the developer is to get the application out as quickly as possible. The developer should not be worried about the configuring various layers of the system. Spring Boot helps us to remove that hassle and helps us to build us stand-alone, production-ready applications that. With that definition, you might be feeling that this framework is just for small level applications. But that is not true. You can build fairly complex systems using this framework.There are a lot of reasons why people started moving on from the Spring framework to the smaller level frameworks. One of them which makes the most sense is the complexity. As Spring itself is a huge framework, its not always easy to get started and build the application. You need to know a lot of things before you can start building the application. Spring framework was originated to solve the commonly occurring problems in the Companies and providing a single framework that can solve them all. But as time went by, building a simple CRUD based application become pretty hard in the case of Spring framework and Spring Boot came to the rescue.Most of the Java developers make use of the official IDE provided by the IntelliJ community for carrying out the development work of there project. We are going to use this as well.Maven is used for handling the packages required to run the application and other basic requirements to make it work. This helps us to handle all the dependencies easily. Without Maven, you will have to download each and every dependency and download all the jar files and handle the full cycle of updates which itself is a quite hectic process. Maven does it by introducing an XML file that contains the name and version of the package that you need for the development of the given project. This file is known asI will be working on Java 8 in this tutorial. You will also have to JAVA_HOME environment variable as well. Try running these two commands to find if you are set up properly or not.It should give you output like as follows:For setting, try this:Result for MAC will be,Open up your IDE and create a Maven project with basic defaults selected. Choose some random GroupId and Artifact ID.Find thefile and add the following configuration. Thepart in the file tells that we are going to use given parent and include all the jars that are present in the given group and given version. After adding this data to yourfile you will have to update the Maven. In most of the cases, you will see a notification in the IDE itself to update it. Otherwise, you can find it in the IDE’s navbar.Now that our dependencies are sorted, let’s start by building the entry point to the project. To set up the entry point, create a package in the directorywith whatever name. In the package create a Java class with a name of your choice. First line contains the name of the package that you created. In the 6th line, you are letting the Spring Boot framework know that this entry point of the project by annotating the class which contains the main class. For starting the server you have to call a server starting function with the following line.This is all that was required to build the initial server in Spring Boot. You can click on thebutton. This will run the application. You will see the following output.Now that the server is started, you can head out to the browser and type into find the server. You will get the following error message.That was really easy. It’s really easy to setup a server using the Spring Boot framework. Now we will work to create Controllers and various other things to create a proper set of Rest APIs.Now that we have a simple server set up, let’s move forward and create a valid URL that we can hit and get the response back. For the testing purpose, I am going to create the status API. This API will tell us whether the services of the server are up or not. For this purpose, you will need to have a class annotated with. For more information, you can learn more about the MVC framework. Spring Boot allows us to simply create controllers where we can specify which URL is going to be used to run this particular code. Create a file calledinpackage and add the following code.is the part of the code that tells the Spring Boot that this class should be treated as a controller. Once we have this, we can use the methods which can be used by any controller and written in RestController static class.takes two arguments, where you have to specify path and API Method( GET, POST, PUT). But if you don’t specify anything, it takes GET by default. Rerun the application and head to. You will get themessage.Now, let’s try to pass back data from the Controller. We are going to start with a basicandclass in thepackage. In thefile, we are defining the schema of the standard class along with theandfunctions. These functions will help us to set and get the data for various class variables. In thefile, we are using the same method that we used last time to create an API that allows themethod withendpoint. This time the function is returning back the List data to the endpoint.helps us convert the data in the List to validand sends back the data. Here is how it is going to look on the browser.As we have already know how to set up a basic Rest API, we now are going to think about the system that we are going to create in this guide. For the sake of this tutorial, we are going to work with three entitiesandLet’s start with theentity. For all operations of a, we will need the following methods.Now that we have agreed upon the basics of the APIs that we are going to develop, let’s just add a persistent layer that can persist data. There is a name for adding this persistence layer to the Java, called Java Persistence Layer( JPA) . JPA is a type of ORM( Operation Relational Manager). If you have worked on some other framework, you might have heard about this term. An ORM helps us to reduce our effort by providing build-in methods to query data from the database. We are going to usefor the tutorial purpose. You can go forward and choose any of the databases out there. The only thing that you will have to change is the libraries that you are importing, everything else should stay as it is.For Linux, you can try this command.The first line tells the URL at which Spring could find the database connection. Second-line gives the username of MySQL who is the owner of the database. The third line is the password of the database. The fourth line is the setting that will help you to auto-generate the tables in the database.We will have addanddependecies so that they can take care of handing the persistence layer for us. Add the following code toJust try to build the application once done with the setting. It should build without any error.Here is whatfile looks like. After writing this down, run the application and check the MySQL shell to find the table created.: Sometime mainpackage doesn’t containdepending on the version of Java that you are using. In that case, you will get an error,. All you have to do in that case is add another dependency for,Read this Stack Overflow answer for more details.is the keyword that tells the Spring Boot that the following class should be considered as a table class. Class parameters are fields of the table.With these lines, we are letting the Spring Boot know that the field which is annotated withkeyword, will be treated astells Spring Boot to autogenerate the value of id field( By incrementing the field)andfield specifies the column name. These are required only if we are doing something else than the normal stuff.The database Access layer in Java is given the name of the Repository. A simple repository provides all the basic methods required to find, create and delete entries in the database. Add this code toBasically you have to extend theand create an interface of that. In the params, you have to pass the name of the Java class that you want to extend and type of the primary key being passed (). We can create another file to handle interactions with the DataBase by creating a Service layer. In Java, it is generally done to separate the business logic from. The advantage of using such a service is that Java while building will load all the classes marked as business services as aand it will not have to create an object again and again. We can do that by using theannotation. Here is the content ofand correspondingcode. Looks like we have already discussed most of the stuff in here. Please drop your comments if you are stuck somewhere. Now you are ready to run your application with DataBase connected.That’s all for this part of the guide. With this much knowledge of Spring Boot, you can create any level of complex project( With a bit of googling). Read the following post, if you need to know more on how to test your newly developed APIs.Your reviews are very important. Please leave your reviews in comments section below. You are awesome.