O7planning Org en 11893 Integrating Spring Boot Jpa and h2 D

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Custom Search

o7planning
All Tutorials Java Maven Gradle Servlet/Jsp Spring Struts2 Hibernate Java Web Service JavaFX SWT Oracle ADF Android

Python Swift C# C/C++ Ruby Batch Database Oracle APEX Report Client ECMAScript / Javascript NodeJS ReactJS

AngularJS Bootstrap OS Git SAP Others

Integrating Spring Boot, JPA and H2 Database

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
View more Tutorials:

Spring Boot Tutorials

1- Objective of Lesson  
2- Create a Spring Boot project
3- Entity Class, DAO, DataInit, Controller
4- Configure Spring Boot & H2
5- Run the application
6- Appendix H2

report th
49
Shares

Spring Boot Tutorials


1- Objective of Lesson  
Install Spring Tool Suite into Eclipse
H2 is a open source, compact relational database, written in Java language. H2 installer has very little capacity of
Spring Tutorial for Beginners
about 8MB.
Spring Boot Tutorial for Beginners
One of the interesting features of the  H2 is that you can create an In-Memory Database instead of being stored in
a computer hard drive. This makes query speed and manipulation with data very fast. However, if you select the " Spring Boot Common Properties
In-Memory Database" feature, data exists only when the application works, when the application is shut down, Spring Boot and Thymeleaf Tutorial
the data is also deleted from the memory. Spring Boot and FreeMarker Tutorial
Spring Boot and Groovy Tutorial
Spring Boot and Mustache Tutorial
Spring Boot and JSP Tutorial
Spring Boot, Apache Tiles, JSP Tutorial
Monitoring application with Spring Boot Actuator
Create a Multi Language web application with
Spring Boot

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
The H2 provides you with an administration tool called  H2 Console, and you work with it through  browser. Using multiple ViewResolvers in Spring Boot
Using Twitter Bootstrap in Spring Boot
Spring Boot Interceptors Tutorial
Spring Boot, Spring JDBC and Spring Transaction
Tutorial
Spring JDBC Tutorial
Spring Boot, JPA and Spring Transaction Tutorial
Spring Boot and Spring Data JPA Tutorial
Spring Boot, Hibernate and Spring Transaction
Tutorial
Integrating Spring Boot, JPA and H2 Database
Spring Boot and MongoDB Tutorial
Using Multiple DataSources with Spring Boot and
JPA
Using Multiple DataSources with Spring Boot and
RoutingDataSource
Create a Login Application with Spring Boot,
Spring Security, Spring JDBC
Create a Login Application with Spring Boot,
Spring Security, JPA
Create a User Registration Application with Spring
Boot, Spring Form Validation
In this lesson, I will show you how to create a  Spring Boot project to integrate with the H2 database and use the " Social Login with OAuth2 in Spring Boot
In Memory Database" feature, and configure to use the H2 Console administration tool.
Running background scheduled tasks in Spring
CRUD Restful Web Service with Spring Boot


Example
Spring Boot Restful Client with RestTemplate
There is no many difference if you want to connect to the H2 database, installed on computer (See the
example
appendix at the end of the this post) 
CRUD Example with Spring Boot, REST and
AngularJS
2- Create a Spring Boot project
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
Secure Spring Boot RESTful Service using Basic
Authentication
Secure Spring Boot RESTful Service using Auth0
JWT
Spring Boot File Upload Example
Spring Boot File Download Example
Spring Boot File Upload with jQuery Ajax Example
Spring Boot File Upload with AngularJS Example
Create a Shopping Cart Web Application with
Spring Boot, Hibernate
Thymeleaf Form Select option Example
Spring Email Tutorial
Create a simple Chat application with Spring Boot
and Websocket
Deploying Spring Boot Application on Tomcat
Server
Deploying Spring Boot Application on Oracle
WebLogic Server

On the  Eclipse, create the  Spring Boot project:

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
report this ad

Newest Documents

Undertanding ECMAScript (ES6) Iterables and


Iterators
ECMAScript (ES6) Error Handling Tutorial
Inheritance and polymorphism in ECMAScript
(ES6)
Classes and Objects in ECMAScript (ES6)
ECMAScript (ES6) Modules Tutorial
ECMAScript / Javascript Regular Expressions
Tutorial
ECMAScript (ES6) Loops Tutorial
ECMAScript (ES6) Functions Tutorial
ECMAScript (ES6) Symbols Tutorial
Undertanding Duck Typing in ECMAScript (ES6)

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
report this ad

report this ad

OK, the project has been created.

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
pom.xml

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


2 <project xmlns="http://maven.apache.org/POM/4.0.0"
3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5     <modelVersion>4.0.0</modelVersion>
6  
7     <groupId>com.example</groupId>
8     <artifactId>SpringBootJpaH2</artifactId>
9     <version>0.0.1-SNAPSHOT</version>
10     <packaging>jar</packaging>
11  
12     <name>SpringBootJpaH2</name>
13     <description>Spring Boot + Jpa + H2</description>
14  
15     <parent>
16         <groupId>org.springframework.boot</groupId>
17         <artifactId>spring-boot-starter-parent</artifactId>
18         <version>2.0.1.RELEASE</version>
19         <relativePath/> <!-- lookup parent from repository -->
20     </parent>
21  
22     <properties>

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
23         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
24         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
25         <java.version>1.8</java.version>
26     </properties>
27  
28     <dependencies>
29         <dependency>
30             <groupId>org.springframework.boot</groupId>
31             <artifactId>spring-boot-starter-data-jpa</artifactId>
32         </dependency>   
33         <dependency>
34             <groupId>org.springframework.boot</groupId>
35             <artifactId>spring-boot-starter-thymeleaf</artifactId>
36         </dependency>
37         <dependency>
38             <groupId>org.springframework.boot</groupId>
39             <artifactId>spring-boot-starter-web</artifactId>
40         </dependency>
41  
42         <dependency>
43             <groupId>com.h2database</groupId>
44             <artifactId>h2</artifactId>
45             <scope>runtime</scope>
46         </dependency>
47         <dependency>
48             <groupId>org.springframework.boot</groupId>
49             <artifactId>spring-boot-starter-test</artifactId>
50             <scope>test</scope>
51         </dependency>
52     </dependencies>
53  
54     <build>
55         <plugins>
56             <plugin>
57                 <groupId>org.springframework.boot</groupId>
58                 <artifactId>spring-boot-maven-plugin</artifactId>
59             </plugin>
60         </plugins>
61     </build>
62  
63  
64 </project>

SpringBootJpaH2Application.java

1 package org.o7planning.springbooth2; ?
2  

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
3 import org.springframework.boot.SpringApplication;
4 import org.springframework.boot.autoconfigure.SpringBootApplication;
5  
6 @SpringBootApplication
7 public class SpringBootJpaH2Application {
8  
9     public static void main(String[] args) {
10         SpringApplication.run(SpringBootJpaH2Application.class, args);
11     }
12      
13 }

3- Entity Class, DAO, DataInit, Controller

Person.java

1 package org.o7planning.springbooth2.entity; ?
2  

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
3 import java.util.Date;
4  
5 import javax.persistence.Column;
6 import javax.persistence.Entity;
7 import javax.persistence.GeneratedValue;
8 import javax.persistence.Id;
9 import javax.persistence.Table;
10 import javax.persistence.Temporal;
11 import javax.persistence.TemporalType;
12  
13 @Entity
14 @Table(name = "PERSON")
15 public class Person {
16  
17     @Id
18     @GeneratedValue
19     @Column(name = "Id", nullable = false)
20     private Long id;
21  
22     @Column(name = "Full_Name", length = 64, nullable = false)
23     private String fullName;
24  
25     @Temporal(TemporalType.DATE)
26     @Column(name = "Date_Of_Birth", nullable = false)
27     private Date dateOfBirth;
28  
29     public Long getId() {
30         return id;
31     }
32  
33     public void setId(Long id) {
34         this.id = id;
35     }
36  
37     public String getFullName() {
38         return fullName;
39     }
40  
41     public void setFullName(String fullName) {
42         this.fullName = fullName;
43     }
44  
45     public Date getDateOfBirth() {
46         return dateOfBirth;
47     }
48  
49     public void setDateOfBirth(Date dateOfBirth) {
50         this.dateOfBirth = dateOfBirth;
51     }
52  

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
53 }

PersonDAO  is an interface extended from  CrudRepository<Person, Long>. Spring Data JPA  , which will itself
create you a class to implement this interface at the time of starting the application.

‘ See also:

Spring Boot and Spring Data JPA Tutorial

PersonDAO.java

1 package org.o7planning.springbooth2.dao; ?
2  
3 import java.util.Date;
4 import java.util.List;
5  
6 import org.o7planning.springbooth2.entity.Person;
7 import org.springframework.data.repository.CrudRepository;
8 import org.springframework.stereotype.Repository;
9  
10 @Repository
11 public interface PersonDAO extends CrudRepository<Person, Long> {
12  
13     public List<Person> findByFullNameLike(String name);
14  
15     public List<Person> findByDateOfBirthGreaterThan(Date date);
16  
17 }

The  DataInit implements  ApplicationRunner  interface. It will automatically run at the time when the application
starts. In this class, we will insert some records to the  PERSON table.

DataInit.java

1 package org.o7planning.springbooth2.init; ?
2  
3 import java.text.DateFormat;

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
4 import java.text.SimpleDateFormat;
5 import java.util.Date;
6  
7 import org.o7planning.springbooth2.dao.PersonDAO;
8 import org.o7planning.springbooth2.entity.Person;
9 import org.springframework.beans.factory.annotation.Autowired;
10 import org.springframework.boot.ApplicationArguments;
11 import org.springframework.boot.ApplicationRunner;
12 import org.springframework.stereotype.Component;
13  
14 @Component
15 public class DataInit implements ApplicationRunner {
16  
17     private PersonDAO personDAO;
18  
19     private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
20  
21     @Autowired
22     public DataInit(PersonDAO personDAO) {
23         this.personDAO = personDAO;
24     }
25  
26     @Override
27     public void run(ApplicationArguments args) throws Exception {
28         long count = personDAO.count();
29  
30         if (count == 0) {
31             Person p1 = new Person();
32  
33             p1.setFullName("John");
34  
35             Date d1 = df.parse("1980-12-20");
36             p1.setDateOfBirth(d1);
37             //
38             Person p2 = new Person();
39  
40             p2.setFullName("Smith");
41             Date d2 = df.parse("1985-11-11");
42             p2.setDateOfBirth(d2);
43  
44             personDAO.save(p1);
45             personDAO.save(p2);
46         }
47  
48     }
49      
50 }

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
MainController.java

1 package org.o7planning.springbooth2.controller; ?
2  
3 import org.o7planning.springbooth2.dao.PersonDAO;
4 import org.o7planning.springbooth2.entity.Person;
5 import org.springframework.beans.factory.annotation.Autowired;
6 import org.springframework.stereotype.Controller;
7 import org.springframework.web.bind.annotation.RequestMapping;
8 import org.springframework.web.bind.annotation.ResponseBody;
9  
10 @Controller
11 public class MainController {
12  
13     @Autowired
14     private PersonDAO personDAO;
15  
16     @ResponseBody
17     @RequestMapping("/")
18     public String index() {
19         Iterable<Person> all = personDAO.findAll();
20  
21         StringBuilder sb = new StringBuilder();
22  
23         all.forEach(p -> sb.append(p.getFullName() + "<br>"));
24  
25         return sb.toString();
26     }
27  
28 }

4- Configure Spring Boot & H2

In this example, I will configure the  Spring Boot to use the  H2  as an In-memory Database, which means we
don't need to install the H2 database. It will automatically be created and stored in computer memory.

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
‘ In another case, if you have installed a H2 database on your computer, and want to interact   Spring Boot
application with this database, you can also see the appendix at the bottom of this post

application.properties

1 # To See H2 Console in Browser: ?


2 # http://localhost:8080/h2-console
3 # Enabling H2 Console
4 spring.h2.console.enabled=true
5  
6 # ===============================
7 # DB
8 # ===============================
9  
10 spring.datasource.url=jdbc:h2:mem:testdb
11 spring.datasource.driverClassName=org.h2.Driver
12 spring.datasource.username=sa
13 spring.datasource.password=
14  
15 # ===============================
16 # JPA / HIBERNATE
17 # ===============================
18  
19 spring.jpa.show-sql=true
20 spring.jpa.hibernate.ddl-auto=update
21 spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect

spring.h2.console.enabled=true

This configuration tells the Spring to start the administration tool of the H2 database and you can access this tool
on the browser:

http://localhost:8080/h2-console

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

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
This configuration tells  Spring that you want to use the In-Memory H2 Database.

spring.jpa.hibernate.ddl-auto=update

This configuration tells the  Spring to create (or update) the structure of structure-based table of  Entity classes.
Thus, the PERSON table will automatically be created by the structure of the Person class. 

5- Run the application

On the  Eclipse, run your application:

At this moment, the  H2 Console is also started with the application and you can access this administration tool:

http://localhost:8080/h2-console
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
The  PERSON table has automatically been created based on the structure of the  Person class.

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
Query the  PERSON table:

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
http://localhost:8080

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
6- Appendix H2

‘ Installing H2 Database and Using H2 Console

In case you use H2 (Server):

application.properties (H2 Server)

1 # To See H2 Console in Browser: ?

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
2 # http://localhost:8080/h2-console
3 # Enabling H2 Console
4 spring.h2.console.enabled=true
5  
6 # ===============================
7 # DB
8 # ===============================
9  
10 spring.datasource.url=jdbc:h2:tcp://localhost/~/testdb
11 spring.datasource.driverClassName=org.h2.Driver
12 spring.datasource.username=sa
13 spring.datasource.password=
14  
15 # ===============================
16 # JPA / HIBERNATE
17 # ===============================
18  
19 spring.jpa.show-sql=true
20 spring.jpa.hibernate.ddl-auto=update
21 spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect

View more Tutorials:

Spring Boot Tutorials

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
report this ad

o7planning.org

Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD

You might also like