Spring Boot - H2 DB Spring Boot - JPA+H2 DB: Page 1 of 15
Spring Boot - H2 DB Spring Boot - JPA+H2 DB: Page 1 of 15
Page 1 of 15
Table of Contents (Use Ctrl+Left Click of Mouse to go to topic)
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
<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>
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
Page 5 of 15
last_name VARCHAR(250) NOT NULL,
career VARCHAR(250) DEFAULT NULL
);
SpringbootH2dbApplication
package com.samples.my;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootH2dbApplication {
<!-- 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>
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>
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();
}
@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;
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 {
<!-- 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>
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
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.
Page 15 of 15