1. Overview

In this article, We are going to explain spring boot datasource example. Spring boot make configuration easy to setup datasouce connection, With few configurations, we can connect to database to perform operations. To setup database connection using spring boot requires some basic dependency like spring-boot-starter-jdbc dependency requires for JDBC connection and another dependency for related database Drive.

We have used following technology inside bellow Spring boot datasource example:

  1. Spring Boot
  2. MySQL
  3. Maven
  4. Spring JdbcTemplate
  5. Java 8

2. Example

 

Spring boot datasource example

Spring boot datasource example

  1. pom.xml

It contains spring-boot-starter-jdbc for spring boot database library and mysql-connector-java for MySQL driver library both are required to connect spring boot with a database.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>spring-boot-example</groupId>
    <artifactId>spring-boot-datasource-example</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
    </parent>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>   <!--It contains database base related classes-->
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

    </dependencies>

    <!-- Package as an executable jar -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

application.properties

Database connection related properties stored in application.properties. application.properties is a standard file of spring boot application which contains all configuration related to spring boot application. Remember that application.properties must in your call path root or resource directory properties.

spring.datasource.url=jdbc:mysql://localhost/demo_database
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

 

SpringBootConfig

It’s spring boot startup file. There is no extra configuration related spring boot datasource.

package com.javadeveloperzone;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

/**
 * Created by JavaDeveloperZone on 19-07-2017.
 */

@SpringBootApplication
@ComponentScan
// Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute
public class SpringBootConfig {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootConfig.class, args);            // it wil start application
    }
}

EmployeeController

A controller will take require from a client and send all Employee List list will be fetched from the database.

package com.javadeveloperzone.controller;

import com.javadeveloperzone.dao.EmployeeDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by JavaDeveloperZone on 19-07-2017.
 */
@RestController
public class EmployeeController {

    @Autowired
    private EmployeeDAO employeeDAO;

    @RequestMapping("/getEmployeeList")
    public java.util.List getEmployeeList() {
        return employeeDAO.getEmployeeList();
    }
}

EmployeeDAO

Its important part of communication with a database. Here JdbcTemplate is @Autowired which automatically find out datasouce. Using JdbcTemplate we can perform communication with database and perform operations with database.

package com.javadeveloperzone.dao;

import com.javadeveloperzone.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by JavaDeveloperZone on 03-08-2017.
 */
@Component
public class EmployeeDAO {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    public java.util.List<Employee> getEmployeeList() {
        List<Map<String, Object>> maps = jdbcTemplate.queryForList("select * from employee");
        return maps.stream().map(map -> {
            Employee employee = new Employee();
            employee.setEmployeeName(map.get("employeeName").toString());
            employee.setEmployeeId((Integer) map.get("employeeId"));
            employee.setEmployeeRole((String) map.get("employeeRole"));
            return employee;
        }).collect(Collectors.toList());
    }
}

Employee

package com.javadeveloperzone.model;

/**
 * Created by JavaDeveloperZone on 03-08-2017.
 */
public class Employee {
    private int employeeId;
    private String employeeName;
    private String employeeRole;

    public int getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }

    public String getEmployeeRole() {
        return employeeRole;
    }

    public void setEmployeeRole(String employeeRole) {
        this.employeeRole = employeeRole;
    }

    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
}

Database Structure

Spring boot mysql database table information

Spring boot MySQL database table information

Run spring boot application

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.4.RELEASE)

2017-08-04 10:10:13.530  INFO 157272 --- [           main] com.javadeveloperzone.SpringBootConfig   : Starting SpringBootConfig on Mahesh with PID 157272 (F:\extrawork\spring-boot\spring-boot-database-example\target\classes started by Lenovo in F:\extrawork\spring-boot\spring-boot-database-example)
2017-08-04 10:10:13.546  INFO 157272 --- [           main] com.javadeveloperzone.SpringBootConfig   : No active profile set, falling back to default profiles: default
2017-08-04 10:10:13.738  INFO 157272 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot[email protected]74a10858: startup date [Fri Aug 04 10:10:13 IST 2017]; root of context hierarchy
2017-08-04 10:10:16.539  INFO 157272 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-08-04 10:10:16.539  INFO 157272 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2017-08-04 10:10:16.539  INFO 157272 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.15
2017-08-04 10:10:16.678  INFO 157272 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-08-04 10:10:16.682  INFO 157272 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2966 ms
2017-08-04 10:10:16.836  INFO 157272 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-08-04 10:10:16.836  INFO 157272 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-08-04 10:10:16.836  INFO 157272 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-08-04 10:10:16.836  INFO 157272 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-08-04 10:10:16.836  INFO 157272 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-08-04 10:10:17.566  INFO 157272 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot[email protected]74a10858: startup date [Fri Aug 04 10:10:13 IST 2017]; root of context hierarchy
2017-08-04 10:10:17.678  INFO 157272 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/getEmployeeList]}" onto public java.util.List com.javadeveloperzone.controller.EmployeeController.getEmployeeList()
2017-08-04 10:10:17.687  INFO 157272 --- [           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-08-04 10:10:17.687  INFO 157272 --- [           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-08-04 10:10:17.707  INFO 157272 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-08-04 10:10:17.707  INFO 157272 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-08-04 10:10:17.753  INFO 157272 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-08-04 10:10:17.988  INFO 157272 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-08-04 10:10:18.035  INFO 157272 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-08-04 10:10:18.050  INFO 157272 --- [           main] com.javadeveloperzone.SpringBootConfig   : Started SpringBootConfig in 5.286 seconds (JVM running for 6.6)

3. Conclusion

In this article, We learn that how spring boot make database connection easy with minimum configuration and make our development easy and fast.

Spring boot datasource example output

Spring boot datasource example output

Spring boot datasource example output

4. References

Spring Boot Datasource Document

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No

Leave a Reply

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