Kotlin – Integrate H2 database with Spring JPA( by Spring Boot) in Embedded mode

H2 database is a pure Java, open source and very fast engine. We can use H2 for development, testing and performance benchmarking. So in the tutorial, JavaSampleApproach will show how to integrate H2 database with Kotlin SpringBoot and Spring JPA in Embedded mode.

I. H2 database and SpringBoot integration

H2 database has small footprint (smaller than 1.5 MB) with low memory requirements. It supports for multiple schemas and standard SQL, JDBC API. We can use H2 with disk based or in-memory databases.

H2 can be built by following mode:
– Embedded mode (local connections)
– Server mode (remote connections)
– Mixed mode (local and remote connections)

In the tutorial, We focus on Embedded mode to integrate H2 database and SpringBoot Application.

kotlin h2 springboot jpa - architecture - H2-Embedded

How to configure it with SpringBoot?
-> Spring Boot has a built in H2 database, so We just add below dependency:

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

H2 supports a convenient web based data console to interact with database while the development:

kotlin h2 springboot jpa - architecture - H2-Database-console

II. Practice

In the tutorial, We create a Spring JPA Web application which uses Spring JPA to interact with H2 database in Embedded mode.

Step to do:
– Create Kotlin SpringBoot project
– Configure H2 database
– Implement Kotlin Spring JPA Web Application
– Run & check results

1. Create Kotlin SpringBoot project

Using SpringToolSuite, create a SpringBoot project. Then add list dependencies {web, jpa, h2}:

...
 
<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>
</dependency>
 
...

2. Configure H2 database

Open application.properties file, add configurations:


spring.h2.console.enabled=true
spring.h2.console.path=/h2_console
spring.datasource.url=jdbc:h2:file:~/h2/testdb
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql=true

Set spring.h2.console.enabled is true to enable web console of H2 database. spring.h2.console.path is used to define H2 console’s url.
Default setting values of H2 database:

– username/password: sa/’blank’
– driverClassName: org.h2.Driver
– datasource.url: jdbc:h2:mem:testdb

Important!:
– jdbc:h2:mem is used to define In-memory databases.
– jdbc:h2:file is used to define disk-based databases.

3. Implement Kotlin Spring JPA Web Application

3.1 Create Customer model


package com.javasampleapproach.kotlin.h2.model

import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.Table

@Entity
@Table(name = "customer")
public class Customer(
    @Id
    val id: Long = -1,
 
    @Column(name = "firstname")
    val firstName: String = "",
 
    @Column(name = "lastname")
    val lastName: String = ""		
){
	override fun toString(): String{
        return "Customer[id=${id}, firstName=${firstName}, lastName=${lastName}]"
	}
}

Annotation @Entity indicates that Customer is an Entity and @Table specifies the primary table (name customer) for the annotated @Entity.
@ID specifies the primary key and @GeneratedValue indicates generation strategy for value of primary key.

@Column: mapped column (in the table) for persistent fields (in Java class).

3.2 Create CustomerRepository

This interface helps us do all CRUD functions for class Customer.


package com.javasampleapproach.kotlin.h2.repository

import org.springframework.data.repository.CrudRepository
import com.javasampleapproach.kotlin.h2.model.Customer

interface CustomerRepository: CrudRepository{
    fun findByLastName(lastName: String): List
} 

3.3 Create a WebController

Create 3 @RequestMapping:
– @RequestMapping(“/save”)
– @RequestMapping(“/findall”)
– @RequestMapping(“/findbyid”)


package com.javasampleapproach.kotlin.h2.controller

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
 
import com.javasampleapproach.kotlin.h2.model.Customer
import com.javasampleapproach.kotlin.h2.repository.CustomerRepository
 
@RestController
class WebController {
	
    @Autowired
    lateinit var repository: CustomerRepository
       
    @RequestMapping("/save")
    fun process(): String{
        repository.save(Customer(1, "Jack", "Smith"))
        repository.save(Customer(2, "Adam", "Johnson"))
        repository.save(Customer(3, "Kim", "Smith"))
        repository.save(Customer(4, "David", "Williams"))
        repository.save(Customer(5, "Peter", "Davis"))
        return "Done"
    }
       
       
    @RequestMapping("/findall")
    fun findAll(): String{
        var result = ""
		
        for(cust in repository.findAll()){
            result += cust.toString() + "
" } return result } @RequestMapping("/findbyid") fun findById(@RequestParam("id") id: Long): String{ return repository.findOne(id).toString() } @RequestMapping("/findbylastname") fun fetchDataByLastName(@RequestParam("lastname") lastName: String): String{ var result = "" for(cust in repository.findByLastName(lastName)){ result += cust.toString() + "
" } return result } }

In the web controller methods which are annotated by @RequestMapping, we have used some methods of autowired repository which are implemented interface CrudRepository:

<S extends T> S save(S entity); //for @RequestMapping("/save")
T findOne(ID id); //for @RequestMapping("/findbyid")
Iterable<T> findAll(); //for @RequestMapping("/findall")

and the method findByLastName that we create in our interface CustomerRepository.


List findByLastName(String lastName);

4. Run & check results

Build and Run the SpringBoot with commandlines: mvn clean install and mvn spring-boot:run.
Make a request: http://localhost:8080/h2_console

kotlin h2 springboot jpa - architecture - H2-database-make-console-request

Input login’s info as above image. Then press Connect, and makes a first select for customer table:

kotlin h2 springboot jpa - architecture - H2-database-first-view

Make a request: http://localhost:8080/save

kotlin h2 springboot jpa - architecture - h2-database-save-request

Now again select customer table:

kotlin h2 springboot jpa - architecture - h2-database-select-customers

Make a request: http://localhost:8080/findall,

kotlin h2 springboot jpa - architecture - h2-database-findall

Make a request http://localhost:8080/findbyid?id=5,

kotlin h2 springboot jpa - architecture - h2-database-find-by-id

Now, do restart the SpringBoot App, then select customer table again:

kotlin h2 springboot jpa - architecture - h2-database-customer-after-restart

Why?
-> Because we use Disk-memory database by setting: spring.datasource.url=jdbc:h2:file:~/h2/testdb.

III. Sourcecode

KotlinSpringBootH2Integration

38 thoughts on “Kotlin – Integrate H2 database with Spring JPA( by Spring Boot) in Embedded mode”

  1. This is very interesting, You’re a very skilled blogger.
    I have joined your feed and look forward to seeking more of your fantastic post.
    Also, I’ve shared your web site in my social networks!

  2. Sweet blog! I found it while browsing on Yahoo News.
    Do you have any suggestions on how to get listed in Yahoo News?
    I’ve been trying for a while but I never seem to get there!
    Appreciate it

  3. Howdy, i read your blog from time to time and i own a
    similar one and i was just curious if you get a lot of spam feedback?
    If so how do you stop it, any plugin or anything you can advise?

    I get so much lately it’s driving me crazy so any support is very much
    appreciated.

  4. After exploring a handful of the blog posts on your website, I
    seriously like your way of writing a blog. I added it to my bookmark site list and will be checking back soon. Please visit my web site too and let me know your opinion.

  5. What’s Going down i’m new to this, I stumbled upon this I’ve found It absolutely useful and it has helped me out loads.
    I hope to contribute & assist other customers like its helped me.
    Good job.

  6. Admiring the hard work you put into your site and in depth information you offer.
    It’s great to come across a blog every once
    in a while that isn’t the same old rehashed information. Great read!
    I’ve saved your site and I’m including your
    RSS feeds to my Google account.

  7. Hi there! Do you know if they make any plugins to help with
    Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good
    gains. If you know of any please share. Thanks!

  8. This is the right blog for anyone who wishes to understand this topic.
    You know a whole lot its almost tough to argue with
    you (not that I really will need to…HaHa).
    You certainly put a brand new spin on a subject that’s been written about for years.
    Wonderful stuff, just great!

  9. I really like what you guys tend to be up too. This type of clever work and coverage!

    Keep up the excellent works guys I’ve incorporated you guys to
    my own blogroll.

  10. Hey there! I know this is kind of off topic but I was wondering which blog platform are
    you using for this website? I’m getting fed up of WordPress because
    I’ve had problems with hackers and I’m looking at options for another
    platform. I would be fantastic if you could point
    me in the direction of a good platform.

  11. I’ve been exploring for a bit for any high quality articles or weblog posts in this kind of area .
    Exploring in Yahoo I ultimately stumbled upon this site.

    Studying this information So i’m happy to show that I’ve an incredibly just right uncanny feeling I found out just what I
    needed. I such a lot unquestionably will make
    certain to don?t overlook this web site and give it a glance regularly.

  12. I blog quite often and I genuinely appreciate your content.
    This article has really peaked my interest.

    I’m going to book mark your site and keep checking for new information about once a week.
    I opted in for your RSS feed too.

  13. Oh my goodness! Amazing article dude! Thanks, However I
    am experiencing troubles with your RSS. I don’t know the reason why I can’t subscribe
    to it. Is there anybody having the same RSS issues? Anybody who
    knows the answer can you kindly respond? Thanks!!

  14. Hi, i believe that i saw you visited my weblog so i
    got here to go back the choose?.I am trying to find issues to
    improve my web site!I suppose its good enough to use some of your concepts!!

  15. I’m not sure where you are getting your info, but good topic.
    I needs to spend some time learning much more or understanding more.
    Thanks for magnificent information I was looking for
    this information for my mission.

  16. wonderful submit, very informative. I wonder why the other experts of this
    sector do not realize this. You should continue your writing.

    I am sure, you have a huge readers’ base already!

  17. you are in reality a excellent webmaster.
    The website loading speed is incredible. It kind of feels
    that you’re doing any distinctive trick. In addition, The contents are masterpiece.
    you have done a fantastic job in this subject!

  18. After looking at a few of the articles on your web page, I truly like your technique
    of blogging. I saved as a favorite it to my bookmark webpage list
    and will be checking back soon. Please check out my website too and tell me what you think.

  19. Oh my goodness! Amazing article dude! Many thanks, However I am going through
    problems with your RSS. I don’t understand why I am unable to subscribe to it.
    Is there anyone else having the same RSS problems? Anyone that knows the solution will you
    kindly respond? Thanks!!

Leave a Reply

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