Nearby lessons

9 of 10

Spring Boot - In-Memory Databases (H2)

📌 What You Will Learn
  • Understand Spring Boot - In-Memory Databases (H2)
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Spring Boot - In-Memory Databases (H2) step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

run(String... args) method

package com.durgasoft;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.CommandLineRunner;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication

@ComponentScan

public class StudentappApplication implements CommandLineRunner{

@Autowired

private DataSource dataSource;

public static void main(String[] args) {

SpringApplication.run(StudentappApplication.class, args);

}

@Override

public void run(String... args) throws Exception {

System.out.println("Connection Pooling : "+dataSource);

  • Apply a particular Connection pooling Mechanism:

a)case-1: only Hikary Connection Pooling, No Tomcat JDBC and No Apache DBCP2

In pom.xml

-------------

No changes , normal pom.xml.

Bydefault, Spring boot will search for Hikary Connection pooling mechanism.

If we run the application then we will get the following output.

---Spring Boot logo----

----

Connection Pooling : HikariDataSource (HikariPool-1)

run(String... args) method

Apache DBCP2 Connection pooling

In pom.xml: Exclude Hikary Connection Pooling in spring-boot-starter-jdbc and provide

tomcat-jdbc dependency.

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-jdbc</artifactId>

<exclusions>

<exclusion>

<groupId>com.zaxxer</groupId>

<artifactId>HikariCP</artifactId>

</exclusion>

</exclusions>

</dependency>

<dependency>

<groupId>org.apache.tomcat</groupId>

<artifactId>tomcat-jdbc</artifactId>

<version>9.0.10</version>

</dependency>

------

</dependencies>

If we run the application then we will get the following output.

---Spring Boot logo----

----

Connection Pooling : org.apache.tomcat.jdbc.pool.DataSource@6438a7fe{----}

Example02
Loading editor…

run(String... args) method

In pom.xml: Exclude "Hikary" and "Tomcat Jdbc" Connection Pooling mechanisms in

"Spring-Boot-Starter-jdbc". and include Apache DBCP2 dependency.

EX:

---

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-jdbc</artifactId>

<exclusions>

<exclusion>

<groupId>org.apache.tomcat</groupId>

<artifactId>tomcat-jdbc</artifactId>

</exclusion>

<exclusion>

<groupId>com.zaxxer</groupId>

<artifactId>HikariCP</artifactId>

</exclusion>

</exclusions>

</dependency>

<dependency>

<groupId>org.apache.commons</groupId>

<artifactId>commons-dbcp2</artifactId>

<version>2.1</version>

</dependency>

-------

</dependencies>

If we run the application then we will get the following output.

---Spring Boot logo----

----

Connection Pooling : org.apache.commons.dbcp2.BasicDataSource@7c8f9c2e

For all the above cases we have to use the following content in application.properties file.

application.properties

------------------------

server.port=1234

spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver

spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe

spring.datasource.username=system

spring.datasource.password=durga

If we want to use any other Connection Pooling Mechanisms like C3PO or proxool in Spring

boot applications then we have to use the following steps.

  • Provide Connection pooling mechanisms dependency in pom.xml file.
  • Provide "spring.datasource.type" property in application.properties file.

EX: C3P0 Connection Pooling Mechnaims:

----------------------------------------

  • Prepare c3p0.properties file under "src/main/resources"

c3p0.properties

----------------

c3p0.initialPoolSize = 10

c3p0.maxPoolSize = 10

c3p0.maxStatements = 20

c3p0.maxIdleTime = 20000

  • Provide "spring.datasource.type" property in application.properties file:

application.properties

-----------------------

spring.datasource.type = com.mchange.v2.c3p0.ComboPooledDataSource

----

----

  • Add c3p0 dependency in pom.xml file and exclude Hikary in pom.xml:

pom.xml

------

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-jdbc</artifactId>

<exclusions>

<exclusion>

<groupId>com.zaxxer</groupId>

<artifactId>HikariCP</artifactId>

</exclusion>

</exclusions>

<dependency>

<groupId>c3p0</groupId>

<artifactId>c3p0</artifactId>

<version>0.9.1.2</version>

</dependency>

-----

</dependecies>

EX:

----

c3p0.properties

-----------------

c3p0.initialPoolSize = 10

c3p0.maxPoolSize = 10

c3p0.maxStatements = 20

c3p0.maxIdleTime = 20000

------------------------

server.port=1234

spring.datasource.driver-class-name=oracle.jdbc.OracleDriver

spring.datasource.url==jdbc:oracle:thin:@localhost:1521:xe

spring.datasource.username=system

spring.datasource.password=durga

spring.datasource.type = com.mchange.v2.c3p0.ComboPooledDataSource

CustomConnectionPoolingApplication.java

----------------------------------------

package com.durgasoft;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.CommandLineRunner;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class CustomconnectionpoolingApplication implements CommandLineRunner {

@Autowired

private DataSource dataSource;

public static void main(String[] args) {

SpringApplication.run(CustomconnectionpoolingApplication.class, args);

}

@Override

public void run(String... args) throws Exception {

System.out.println("Connection Pooling Data Source : "+dataSource);

}

}

Example03
Loading editor…

run(String... args) method

sd/maven-4.0.0.xsd">

Example04
Loading editor…

run(String... args) method

on>

Example05
Loading editor…

run(String... args) method

Example06
Loading editor…

run(String... args) method

Example07
Loading editor…

run(String... args) method

Example08
Loading editor…

run(String... args) method

Example09
Loading editor…

run(String... args) method

Example10
Loading editor…

run(String... args) method

Example11
Loading editor…

run(String... args) method

Example12
Loading editor…

In Memory Databases in Spring Boot

------------------------------------

IN enterprise applications, if we want to use traditional Databases then we have to provide

lot of configurations like

  • Install Database
  • Providing Database setups
  • Create Schema
  • Create table
  • Populating Data.
  • Creating dataSource to connect with database

-----

-----

To overcome the above problems, we will use In Memory databases.

In Memory Databases are providing the following Advantages.

Zero project setup or infrastructure

Zero Configuration

Zero Maintainance

Easy to use for Learning, POCs and Unit Tests

Spring Boot provides Simple Configuration to switch between a real database and an in

memory database like H2

In general, In Memory databases are started when application is started and destroyed

when application is stopped.

EX: H2

H2 is a relational database management system written in Java. It can be embedded in Java

applications or run in the client-server mode.

If we want to use H2 Im Memory Database for our applications then we have to use the

following steps.

  • Prepare Spring boot starter project with "web, JDBC" "h2" Dependencies in STS.
  • Provide the following properties in application.properties file:

spring.h2.console.enabled=true

spring.datasource.url=jdbc:h2:mem:testdb

spring.datasource.driverClassName=org.h2.Driver

spring.datasource.username=sa

spring.datasource.password=

  • Prepare SQL script files under "src/main/resources".

schema.sql

-------------

drop table if exists emp1;

create table emp1(ENO number(5) primary key, ENAME varchar2(10), ESAL float(5),

EADDR varchar2(10));

data.sql

--------

insert into emp1 values(111, 'AAA', 5000, 'Hyd');

insert into emp1 values(222, 'BBB', 6000, 'Hyd');

insert into emp1 values(333, 'CCC', 7000, 'Hyd');

insert into emp1 values(444, 'DDD', 8000, 'Hyd');

insert into emp1 values(555, 'EEE', 9000, 'Hyd');

Spring boot application will load and execute these sql scripting files.

EX:

----

schema.sql

-----------

drop table if exists emp1;

create table emp1(ENO number(5) primary key, ENAME varchar2(10), ESAL float(5), EADDR

varchar2(10));

data.sql

----------

insert into emp1 values(111, 'AAA', 5000, 'Hyd');

insert into emp1 values(222, 'BBB', 6000, 'Hyd');

insert into emp1 values(333, 'CCC', 7000, 'Hyd');

insert into emp1 values(444, 'DDD', 8000, 'Hyd');

insert into emp1 values(555, 'EEE', 9000, 'Hyd');

application.properties

-----------------------

server.port=1234

spring.mvc.view.prefix=/WEB-INF/

spring.mvc.view.suffix=.jsp

spring.h2.console.enabled=true

spring.datasource.url=jdbc:h2:mem:testdb

spring.datasource.driverClassName=org.h2.Driver

spring.datasource.username=sa

spring.datasource.password=

H2DatabaseApplication.java

---------------------------

package com.durgasoft;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class H2databaseApplication //implements CommandLineRunner

{

public static void main(String[] args) {

SpringApplication.run(H2databaseApplication.class, args);

}

}

EmployeeController.java

------------------------

package com.durgasoft.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.RequestMapping;

import com.durgasoft.dao.EmployeeDao;

import com.durgasoft.dto.Employee;

@Controller

public class EmployeeController {

@Autowired

private EmployeeDao employeeDao;

@RequestMapping("getallemployees")

public String getAllEmployees(ModelMap map) {

List<Employee> allEmployees = employeeDao.getAllEmployees();

map.addAttribute("allEmployees", allEmployees);

return "employeesdetails";

}

}

EmployeeDao.java

-----------------

package com.durgasoft.dao;

import java.util.List;

import com.durgasoft.dto.Employee;

public interface EmployeeDao {

public List<Employee> getAllEmployees();

}

Employee.java:

-------------------

package com.durgasoft.dto;

In Memory Databases in Spring Boot

Example14
Loading editor…

In Memory Databases in Spring Boot

EmployeeDaoImpl.java

---------------------

package com.durgasoft.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.stereotype.Repository;

import com.durgasoft.dto.Employee;

@Repository

public class EmployeeDaoImpl implements EmployeeDao {

@Autowired

private JdbcTemplate jdbcTemplate;

@Override

public List<Employee> getAllEmployees() {

List<Employee> list = jdbcTemplate.query("select * from emp1", (rs, rowNum)

-> {

Employee emp = new Employee();

emp.setEno(rs.getInt("ENO"));

emp.setEname(rs.getString("ENAME"));

emp.setEsal(rs.getFloat("ESAL"));

emp.setEaddr(rs.getString("EADDR"));

return emp;

});

return list;

}

}

employeedetails.jsp:

--------------------------

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

<h2 style="color: red;" align="center">Employees Details</h2>

<table align="center" border="1">

<tr><th>ENO</th><th>ENAME</th><th>ESAL</th><th>EADDR</th></tr>

<c:forEach var="emp" items="${allEmployees}">

<tr>

<td>${emp.eno}</td>

<td>${emp.ename}</td>

<td>${emp.esal}</td>

<td>${emp.eaddr}</td>

</tr>

</c:forEach>

</table>

</body>

</html>

pom.xml

-----------

Example15
Loading editor…

In Memory Databases in Spring Boot

sd/maven-4.0.0.xsd">

Example16
Loading editor…

In Memory Databases in Spring Boot

Example17
Loading editor…

In Memory Databases in Spring Boot

Example18
Loading editor…

In Memory Databases in Spring Boot

Example19
Loading editor…

In Memory Databases in Spring Boot

Example20
Loading editor…

In Memory Databases in Spring Boot

Example21
Loading editor…

In Memory Databases in Spring Boot

Example22
Loading editor…

In Memory Databases in Spring Boot

Example23
Loading editor…

In Memory Databases in Spring Boot

Example24
Loading editor…

In Memory Databases in Spring Boot

To get H2 In memory Database use the following End Point.

http://localhost:1234/h2-console and click on "Connect" button.

To get all Employees list use the following End Point.

http://localhost:1234/getallemployees

Example25
Loading editor…
📝 Key Takeaways
  • Key ideas of Spring Boot - In-Memory Databases (H2) explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.