This is going to be an introductory blog post on spring boot 2. This blog will serve as a reference for new recruits in Rokomari. We are going to use Intellij as this is common practice in Rokomari to run spring boot projects in Intellij. We are going to build a rest service using spring boot with mysql as its data source.

First you have to have java in your system. Follow following links

  1. https://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html
  2. https://www.mkyong.com/java/how-to-set-java_home-on-windows-10/
  3. http://www.mkyong.com/java/how-to-set-java_home-environment-variable-on-mac-os-x/
  4. https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

Also you have to install Intellij on your sytem. After installing, follow processes below.

Creating Spring Boot Application:

First we are going to create project in Intellij. For that, after opening Intellij, go to

File -> new -> project

After getting this window, select “Spring Initializr”. You can see that, Initializr Service URL is set as https://start.spring.io. You can also create project directly from going into that URL but I am going to show it with inltellij itself. Click Next.

Here, group and artifact ID is needed to create this project. Group ID should be the reverse domain name you control. Artifact ID is name of the jar without version. More on this can be found on https://maven.apache.org/guides/mini/guide-naming-conventions.html. Click Next.

Then, a window will pop-up where you have to mention dependencies which your project will have.

Now, what dependencies I am talking about? Your project may depend on external components and modules. Those are called dependencies of your project. As we are talking about dependencies, let’s talk about maven also.

Spring Boot by default uses maven which is a tool for building and managing any Java-based project. Maven uses project object model (POM) which is an XML file that includes ->

  1. Information about the software project
  2. Configuration details to build that particular project
  3. Any dependencies on external components or modules
  4. The build order.
  5. And many more

Any dependencies you add from this window will be added to your pom.xml file and maven will manage those dependencies. For more information visit https://maven.apache.org/what-is-maven.html and https://www.techopedia.com/definition/27802/maven

Also you have to install maven on your computer. Follow one of these as per your operating system.

  1. http://www.mkyong.com/maven/how-to-install-maven-in-windows/
  2. http://www.mkyong.com/maven/install-maven-on-mac-osx/
  3. http://www.mkyong.com/maven/how-to-install-maven-in-ubuntu/

Now, add following dependencies.

That’s all we need for our project. Click Next and another window will pop-up asking for project name and directory. Click Finish and your project is created.

Your project structure will initially look something like this.

There’s a file called pom.xml which is for maven to use. Upon opening this, you will see project information such as groupId and artifactId. You will also see dependencies which you added before project creation.

Go to src -> main -> java -> {package_name}

You will see main class there. And In there, inside your main method you will see

SpringApplication.run(MainApplication.class, args);

This method starts whole Spring Framework and main class is provided as a parameter to this method.

Go to src -> main -> resources

Here you will see a file called application.properties. SpringApplication will load properties from this file and add them to the Spring Environment. To use Mysql as our data-source, we have to populate this file accordingly.

Copy and paste following code into application.properties.

# DataSource settings: set here configurations for the database connection
spring.datasource.url = jdbc:mysql://localhost:3306/demo-app
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.connection-test-query="SELECT 1"
spring.datasource.test-while-idle=true
spring.datasource.test-on-borrow=true

# Specify the DBMS
spring.jpa.database = MYSQL

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate settings are prefixed with spring.jpa.hibernate.*
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming_strategy = org.hibernate.cfg.ImprovedNamingStrategy

Here, spring.datasource.url is location of your database. First create database in your localhost and set that URL in this property.

spring.datasource.username and spring.datasource.password is your username and password to access your database.

spring.datasource.username.ddl-auto is an important property. Here, it is set as “update” which modify schema upon restart. Follow links below to explore different kinds.

  1. https://stackoverflow.com/questions/42135114/how-does-exactly-spring-jpa-hibernate-ddl-auto-property-works-in-spring
  2. https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html

I would suggest readers to search in Google about other properties if curious.

Before running the project, make sure your Mysql database application is running on port 3306. Now, run the project and in the log you will see something like this “Tomcat started on port(s): 8080”.  That is the magic of spring boot. You didn’t need to setup tomcat server separately. Tomcat server is embedded into application itself. You just run the application and voila. You now have a web-application which listens to certain port.

Now, of course this application doesn’t do much. Let’s create an online problem sharing platform where users can add, update and delete problems. Let’s say a problem can have problem id, problem title and problem description.

So, initially we will have a problem table and columns of that table will be problem id, problem title and problem description. So we should create a table separately with these fields with appropriate constraints and then communicate with it from spring application. Right? Well, yes. But Spring makes it a lot easier to work with table creation and query. Spring uses JPA (Java Persistent API) which is java’s standard API for ORM (object-relational-mapping) to handle communication with database. Now, what is ORM? In ORM, You will just write classes in your code and these will serve as tables in your database. Member variables of a class will become columns of a table and with class methods you can interact with table. More info can be found here

  1. https://stackoverflow.com/questions/1152299/what-is-an-object-relational-mapping-framework
  2. https://en.wikipedia.org/wiki/Object-relational_mapping

JPA is only a specification to support ORM. Hibernate is one of the most well-known implementations of JPA. Spring also has a project called “Spring Data” which is created to make it easier to work with different databases. Spring data supports JPA via the “Spring Data JPA” sub-project. Previously, we added JPA as dependency in our project. It by default includes spring-data-jpa, spring-orm and hibernate as its implementation.

Now that, database dependency is done with, let’s talk about our project architecture. MVC (model-view-controller) is one of the most famous architecture for separation of concern. “Spring MVC” makes it easier to work with this architecture. Previously we added “web” as our dependency. It includes tomcat and Spring MVC.

Enough chitchat. Let’s start with the project.

Project Structure is given above. We have created 4 packages -> controller, entity, repository, service.

entity package:

In Problem class you will see following code snippet

@Entity
public class Problem {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String description;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

You can see Problem class with 3 variables and corresponding getters and setters. You can also see above our class name @Entity is written.What is this? This thing is called annotation (prefix starts with @). Annotation is used in spring framework so that we can configure behaviors of the spring framework easily. Here, @Entity defines that this class can be mapped to a table. If you run this project, you will see that a table called problem is created automatically. It’s because Spring JPA saw this class annotated with @Entity and created a table with same name with same fields.

Next, you can see @Id is used above id variable. This is saying that, id is our primary key. @GeneratedValue(strategy =GenerationType.IDENTITY) is also used above this field which makes this field auto-generated.

repository package:

In ProblemRepository class you will see following code snippet

public interface ProblemRepository extends CrudRepository<Problem, Long> {
}

Here, We made our custom ProblemRepository class which extends from CrudRepository. CrudRepository basically provides CRUD functionality for the entity class that is being managed. Here, CrudRepository takes entity class as its first argument and id(primary key) of that class as second. Basically ProblemRepository is responsible now for any kind of CRUD operation on our problem table.

service package:

In ProblemService class you will see following code snippet

@Service
public class ProblemService {

    @Autowired
    ProblemRepository problemRepository;

    public List<Problem> getAllProblems()   {
        List<Problem> problems = new ArrayList<>();

        for(Problem problem : problemRepository.findAll())   {
            problems.add(problem);
        }
        return problems;
    }

    public void createProblem(Problem problem) {
        problemRepository.save(problem);
    }

    public void updateProblem(Problem problem) {
        problemRepository.save(problem);
    }

    public void deleteProblem(Long id) {
        problemRepository.deleteById(id);
    }
}

Here, class is annotated with @Service. That means our business logic will reside here and with @Service annotated Spring MVC behaves accordingly. Here, you will see that a declaration of ProblemRepository is annotated with @Autowired. I am not going to explain it here. Just know that, an instance of ProblemRepository will get populated automatically. We don’t have to create an instance of ProblemRepository ourselves.
Here, our service-end communicates with database-end through repository.In createProblem() method, you can create any problem just by calling problemRepository.save(problem). You can update old problem with same method. You can delete a single problem by calling problemRepository.deleteById(id). Also, you can get all problems by calling problemRepository.findAll() which returns an Iterable<Problem>. We can do CRUD operations on database just by calling methods. No Query needed whatsoever.

controller package:

In ProblemController class you will see following code snippet

@RestController
public class ProblemController {

    @Autowired
    private ProblemService problemService;

    @GetMapping("/problems")
    public List<Problem> getAllProblems()   {
        return problemService.getAllProblems();
    }

    @PostMapping("/problems")
    public void createProblem(@RequestBody Problem problem) {
        problemService.createProblem(problem);
    }

    @PutMapping("/problems")
    public void updateProblem(@RequestBody Problem problem) {
        problemService.updateProblem(problem);
    }

    @DeleteMapping("/problems/{id}")
    public void deleteProblem(@PathVariable Long id) {
        problemService.deleteProblem(id);
    }

}

Here class is annotated with @RestController which makes this service restful. Controller basically deals with routing and communication with user. It provides services to user through service-end. It is discouraged to do any kind of business logic in controllers.

@GetMapping, @PostMapping, @PutMapping, @DeleteMapping acts as get, post, put and delete requests respectively. Annotating one of these on a function makes that function able to handle that kind of request.

As an example see createProblem() method. It handles post request with “/problems” routing. @RequestBody is annotated before our parameter which is of Problem type. It ensures that data sent to this particular URL is “Problem” type and it will be mapped accordingly to our problem object. We can then work with that object as we like.

@PathVariable is used to obtain some placeholder from the URL. Here, in @DeleteMapping, URL is given as “/problem/{id}”. Here id is a place holder in URL and you will catch it as it is given with your own variable annotated with @PathVariable.

Run this project and let’s test it with postman.

Create Problem:

Update Problem:

Get All Problems:

Delete Problem:

Code is given here https://github.com/eltonrawn/learn-spring-boot/tree/learn-spring-boot1. Hope this helps.

Previous ArticleNext Article

Leave a Reply

Your email address will not be published. Required fields are marked *