0% found this document useful (0 votes)
122 views

Spring Boot - H2 DB Spring Boot - JPA+H2 DB: Page 1 of 15

This document provides instructions for setting up Spring Boot projects with H2 database integration using both raw JDBC and JPA approaches. For the raw JDBC approach, it describes adding dependencies to the pom.xml, configuring application.properties for the H2 URL and credentials, adding SQL scripts, and accessing the H2 console. For the JPA approach, it again describes configuring the pom.xml and application.properties, but then adds steps to define a model class, repository interface, controller, and application class along with populating data and accessing the console.

Uploaded by

Prem Vinodh
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
122 views

Spring Boot - H2 DB Spring Boot - JPA+H2 DB: Page 1 of 15

This document provides instructions for setting up Spring Boot projects with H2 database integration using both raw JDBC and JPA approaches. For the raw JDBC approach, it describes adding dependencies to the pom.xml, configuring application.properties for the H2 URL and credentials, adding SQL scripts, and accessing the H2 console. For the JPA approach, it again describes configuring the pom.xml and application.properties, but then adds steps to define a model class, repository interface, controller, and application class along with populating data and accessing the console.

Uploaded by

Prem Vinodh
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 15

Spring Boot – H2 DB

Spring Boot – JPA+H2 DB

Page 1 of 15
Table of Contents (Use Ctrl+Left Click of Mouse to go to topic)

“Spring Boot H2 DB”................................................................................................................................4


 Spring Boot Using H2 DB...........................................................................................................4
 Creating a Spring Boot project...............................................................................................4
 pom.xml................................................................................................................4
 application.properties...........................................................................................5
 data.sql..................................................................................................................5
 SpringbootH2dbApplication................................................................................6
 Access the h2 console from the browser..............................................................6
 Spring Boot Using (JPA and H2 DB)..........................................................................................8
 Creating a Spring Boot project...............................................................................................8
 pom.xml................................................................................................................8
 application.properties...........................................................................................9
 Billionaire model..................................................................................................9
 BillionarieRepository.........................................................................................10
 BillionarieController...........................................................................................11
 SpringBootJpaH2dbApplication........................................................................12
 Access the h2 console from the browser............................................................13
 Populate the data using postman........................................................................14
 data.sql................................................................................................................15

Page 2 of 15
Page 3 of 15
“Spring Boot H2 DB”
 Spring Boot Using H2 DB
 Creating a Spring Boot project
 File -> New -> Maven Project -> Next -> Create a simple project (Skip archetype selection) select
the checkbox -> Next
o Group Id -> com.samples.my
o Artifact Id -> springboot-h2db
o Version -> 0.0.1-SNAPSHOT  Finish
 Add the following (highlighted in yellow) to the pom.xml to convert it to a Spring Boot
Application

pom.xml

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLS-
chema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/
maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<groupId>com.samples.my</groupId>
<artifactId>springboot-h2db</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-h2db</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- Adding this dependency will keep the web app running without shutting it down
after startup -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

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

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>

Page 4 of 15
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

 The springboot-h2db project shows error and in the Markers tab

o RCL on the springboot-h2db -> Maven -> Update Project -> Select the springboot-h2db
-> Ok.
o The error goes away.

application.properties

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password

spring.h2.console.enabled=true #http://localhost:8080/h2-console
#spring.h2.console.path=/h2-ui

 By design, the in-memory database is volatile, and data will be lost when we restart the
application.
o We can change this behavior by using file-based storage.
o To do this we need to update the spring.database.url
spring.datasource.url=jdbc:h2:file:/data/demo
data.sql

DROP TABLE IF EXISTS billionaires;

CREATE TABLE billionaires (


id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(250) NOT NULL,

Page 5 of 15
last_name VARCHAR(250) NOT NULL,
career VARCHAR(250) DEFAULT NULL
);

INSERT INTO billionaires (first_name, last_name, career) VALUES


('Aliko', 'Dangote', 'Billionaire Industrialist'),
('Bill', 'Gates', 'Billionaire Tech Entrepreneur'),
('Folrunsho', 'Alakija', 'Billionaire Oil Magnate');

SpringbootH2dbApplication
package com.samples.my;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootH2dbApplication {

public static void main(String[] args) {


SpringApplication.run(SpringbootH2dbApplication.class, args);
}
}

 RCL on springboot-h2db project and Select Run As -> Java Application


o The application starts and it will not stop immediately as we are using the pom
dependency

<!-- Adding this dependency will keep the web app running without shutting it down after
startup -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

Access the h2 console from the browser


 In order to access the h2 console from the browser, you need to have the following property in
your application.properties.
spring.h2.console.enabled=true
 Now you can access the h2 console from the browser at the url:
http://localhost:8080/h2-console
o If you want a custom url instead of default (h2-console) you need to add the
following property to the application.properties:

spring.h2.console.path=/h2-ui

http://localhost:8080/h2-ui

Page 6 of 15
 Ensure the JDBC URL, username and Password match the values in the application.properties file.
 Click on Test Connection to check if the connection is established.
 Once everything is ok, click on Connect and login to the h2 console.
Click on the Billionaries table on the left pane to generate the query in the right pane.
Now Click on Run button and see the results displayed in the bottom frame of the right pane.

Page 7 of 15
 Spring Boot Using (JPA and H2 DB)
 Creating a Spring Boot project
 File -> New -> Maven Project -> Next -> Create a simple project (Skip archetype selection) select
the checkbox -> Next
o Group Id -> com.samples.my
o Artifact Id -> springboot-jpa-h2db
o Version -> 0.0.1-SNAPSHOT  Finish
 Add the following to the pom.xml to convert it to a Spring Boot Application

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLS-
chema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/
maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<groupId>com.samples.my</groupId>
<artifactId>springboot-jpa-h2db</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-jpa-h2</name>
<description>Spring Boot JPA + H2 database example - Rest CRUD Apis</description>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
Page 8 of 15
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

 The springboot-jpa-h2db project shows error and in the Markers tab

o RCL on the springboot-jpa-h2db -> Maven -> Update Project -> Select the springboot-
-> Ok.
jpa-h2db
o The error goes away.

application.properties
spring.h2.console.enabled=true
# default path: http://localhost:8080/h2-console
spring.h2.console.path=/h2-ui
#http://localhost:8080/h2-ui

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto= update

 By design, the in-memory database is volatile, and data will be lost when we restart the
application.
o We can change this behavior by using file-based storage.
o To do this we need to update the spring.database.url
spring.datasource.url=jdbc:h2:file:/data/demo

Billionaire model
package com.samples.my.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
Page 9 of 15
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "Billionaires")
public class Billionaire {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

@Column(name = "career")
private String career;

public Billionaire() {
super();
}

public Billionaire(String firstName, String lastName, String career) {


super();
this.firstName = firstName;
this.lastName = lastName;
this.career = career;
}

// getters and setters

@Override
public String toString() {
return "Billionaire [id=" + id + ", firstName=" + firstName + ", lastName=" +
lastName + ", career=" + career
+ "]";
}
}
BillionarieRepository
package com.samples.my.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import com.samples.my.model.Billionaire;

public interface BillionaireRepository extends JpaRepository<Billionaire, Long> {

// List<Tutorial> findByLastNameContaining(String lastName);


//
// List<Tutorial> findByCareer(String career);
}

Page 10 of 15
BillionarieController
package com.samples.my.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.samples.my.model.Billionaire;
import com.samples.my.repository.BillionaireRepository;

@RestController
@RequestMapping("api")
public class BillinaireController {

@Autowired
BillionaireRepository billionaireRepository;

@GetMapping("/billionaires")
public ResponseEntity<List<Billionaire>> getAllTutorials(@RequestParam(required =
false) String title) {
try {
List<Billionaire> tutorials = new ArrayList<Billionaire>();
if (title == null)
billionaireRepository.findAll().forEach(tutorials::add);
// else
// billionaireRepository.findByTitleContaining(title).forEach(tutorials::add);

if (tutorials.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(tutorials, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}

@GetMapping("/billionaires/{id}")
public ResponseEntity<Billionaire> getTutorialById(@PathVariable("id") long id) {
Optional<Billionaire> billionaireData = billionaireRepository.findById(id);

if (billionaireData.isPresent()) {
return new ResponseEntity<>(billionaireData.get(), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
Page 11 of 15
}

@PostMapping("/billionaires")
public ResponseEntity<Billionaire> createTutorial(@RequestBody Billionaire billion-
aire) {
try {
Billionaire _billionaire = billionaireRepository.save(
new Billionaire(billionaire.getFirstName(), billionaire.getLastName(),
billionaire.getCareer()));
return new ResponseEntity<>(_billionaire, HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}

@PutMapping("/billionaires/{id}")
public ResponseEntity<Billionaire> updateTutorial(@PathVariable("id") long id,
@RequestBody Billionaire billionaire) {
Optional<Billionaire> billionaireData = billionaireRepository.findById(id);

if (billionaireData.isPresent()) {
Billionaire _billionarie = billionaireData.get();
_billionarie.setFirstName(billionaire.getFirstName());
_billionarie.setLastName(billionaire.getLastName());
_billionarie.setCareer(billionaire.getCareer());
return new ResponseEntity<>(billionaireRepository.save(_billionarie), Http-
Status.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}

@DeleteMapping("/billionaires/{id}")
public ResponseEntity<HttpStatus> deleteTutorial(@PathVariable("id") long id) {
try {
billionaireRepository.deleteById(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}

@DeleteMapping("/billionaires")
public ResponseEntity<HttpStatus> deleteAllTutorials() {
try {
billionaireRepository.deleteAll();
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

SpringBootJpaH2dbApplication
package com.samples.my;

import org.springframework.boot.SpringApplication;

Page 12 of 15
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootJpaH2Application {

public static void main(String[] args) {


SpringApplication.run(SpringBootJpaH2Application.class, args);
}
}

 RCL on springboot-jpa-h2db project and Select Run As -> Java Application


o The application starts and it will not stop immediately as we are using the pom
dependency

<!-- Adding this dependency will keep the web app running without shutting it down after
startup -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

Access the h2 console from the browser


 In order to access the h2 console from the browser, you need to have the following property in
your application.properties.
spring.h2.console.enabled=true
 Since we have the property spring.h2.console.path=/h2-ui in application.properties.
 Now you can access the h2 console from the browser at the url:
http://localhost:8080/h2-ui (instead of the default http://localhost:8080/h2-console)

 Ensure the JDBC URL, username and Password match the values in the application.properties file.
 Click on Test Connection to check if the connection is established.
 Once everything is ok, click on Connect and login to the h2 console.
Click on the Billionaries table on the left pane to generate the query in the right pane.
Now Click on Run button and see the results displayed in the bottom frame of the right pane.

Page 13 of 15
Populate the data using postman
 Add one billionarie

 Get all billionaires

Page 14 of 15
data.sql
 If you want to initialize the billionaire table with some data then add the file data.sqal file to the
src/main/resources with the following content.

DROP TABLE IF EXISTS billionaires;

CREATE TABLE billionaires (


id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(250) NOT NULL,
last_name VARCHAR(250) NOT NULL,
career VARCHAR(250) DEFAULT NULL
);

INSERT INTO billionaires (first_name, last_name, career) VALUES


('Aliko', 'Dangote', 'Billionaire Industrialist'),
('Bill', 'Gates', 'Billionaire Tech Entrepreneur'),
('Folrunsho', 'Alakija', 'Billionaire Oil Magnate');

Page 15 of 15

You might also like