H2 database example using hibernate and Spring Boot

Here is a H2 database example using Hibernate and Spring Boot. This example shows you how to create, read, update and delete a record in H2 database. I have used maven to build the project.

h2 database example

Download full source code > H2 example source code (1063)

If you are new to hibernate you can read my Spring Hibernate tutorial.

Introduction to H2 Database

H2 is an open source embedded database built on java ships in a single .jar file. Therefore you can easily embed h2 database into your application. H2 Database has a built in web based console that you can use to interact with the database. You can use H2 database as a in-memory database, embedded database or network database.

You can find more details about H2 Database from H2 Database official website

H2 Database example application

This example application saves request time in a H2 database for each GET request.
h2 example project structure

.pom file

First of all here are the maven dependencies for spring boot to use H2 Database and Hibernate

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mycuteblog</groupId>
    <artifactId>spring-boot-example</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.6.RELEASE</version>
    </parent>

    <dependencies>
        <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>
            <version>${h2.version}</version>
        </dependency>
    </dependencies>

    <!--create an executable jar-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Model Class

ApiRequest.java class to store api request data.

@Entity
@Table(name = "api_request")
public class ApiRequest {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column(name="request_time")
    private Date requestTime;

    public ApiRequest() {
    }

    public ApiRequest(Date requestTime) {
        this.requestTime = requestTime;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Date getRequestTime() {
        return requestTime;
    }

    public void setRequestTime(Date requestTime) {
        this.requestTime = requestTime;
    }
}

DAO class

ApiRequestDao.java class contains methods for CRUD operations with H2 Database

@Repository
public class ApiRequestDao {
 @PersistenceContext
 private EntityManager entityManager;

 
 public void create(ApiRequest apiRequest) {
 entityManager.persist(apiRequest);
 }

 
 public void update(ApiRequest apiRequest) {
 entityManager.merge(apiRequest);
 }

 
 public ApiRequest getApiRequestById(long id) {
 return entityManager.find(ApiRequest.class, id);
 }

 
 public void delete(long id) {
 ApiRequest apiRequest = getApiRequestById(id);
 if (apiRequest != null) {
 entityManager.remove(apiRequest);
 }
 }

Service class

ApiRequestService.java acts between DAO and our controller

@Transactional
public class ApiRequestService {

@Autowired
 private ApiRequestDao apiRequestDao;

 public void create(ApiRequest apiRequest) {
 apiRequestDao.create(apiRequest);
 }
}

Controller class

ApiRequestController.java is the spring web controller which receives the http GET request an process.

@RestController
@EnableAutoConfiguration
public class ApiRequestController {

    @Autowired
    private ApiRequestService apiRequestService;

    private static final Logger logger = LoggerFactory.getLogger(ApiRequestController.class);

    @RequestMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map&amp;lt;String, String&amp;gt; getHome() {
        logger.info("Api request received");

        Map&amp;lt;String, String&amp;gt; response = new HashMap&amp;lt;String, String&amp;gt;();
        try {
            ApiRequest apiRequest = new ApiRequest(new Date());
            apiRequestService.create(apiRequest);
            response.put("status", "success");
        } catch (Exception e) {
            logger.error("Error occurred while trying to process api request", e);
            response.put("status", "fail");
        }

        return response;
    }
}

Main method

We use main method in WebApplication.java to run the application

@SpringBootApplication
public class WebApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class, args);
    }
}

Property file

application.properties file contains all the required configurations to connect h2 database and run Spring Boot

server.port = 8080
java.version=1.7

#spring.datasource.url = jdbc:h2:mem:app_db;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.url = jdbc:h2:file:~/h2/app_db;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username = sa
spring.datasource.password =
spring.datasource.driverClassName = org.h2.Driver
spring.jpa.hibernate.ddl-auto = update

H2 Database console

This is an optional step. Add this class if you wish to enable the h2 database console within your app. Once you add this, H2 database console will be available at http://localhost:8080/console.

@Configuration
public class WebConfiguration {
    @Bean
    ServletRegistrationBean h2servletRegistration(){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean( new WebServlet());
        registrationBean.addUrlMappings("/console/*");
        return registrationBean;
    }
}

That’s all. Build the project and run using mvn spring-boot:run command. Visit following url from your browser to record a api call.
http://localhost:8080

Download full source code > H2 example source code (1063)

Enjoyed this article? Share with friends

  • Instead of the optional step where you enable the console, it can easily be done by adding `spring.h2.console.enabled=true` in the application.properties file. No need for extra code

Subscribe

Subscribe to our email feed and never miss a post

Join Us