BlogContacts
BlogGamesContacts

{{item}}

H2 database example

24.10.2020

Java, Spring, H2, JDBC

Source code
A small application with an in-memory database and a web interface, which is build on spring-webmvc and h2 database engine. Project Users.In-memory databases are fast and lightweight, so they can be used in any kind of project. This is an example application, which uses spring-jdbc and has one tata source. The database consists of one table Users and the frontend consists of one servlet H2console.
See extended version with spring-data-jpa and GraphQL API: Simple GraphQL implementation.
application.properties
datasource.dbname=users
datasource.script=classpath:resources/users.sql
Java
package org.drakonoved.h2;

@Configuration
@PropertySource(value = "classpath:resources/application.properties")
public class Application implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) {
        // This servlet lets the H2 Console be used in a
        // standard servlet container such as Tomcat or Jetty.
        servletContext
                .addServlet("H2console", WebServlet.class)
                .addMapping("/console/*");

        AnnotationConfigWebApplicationContext applicationContext =
                new AnnotationConfigWebApplicationContext();

        applicationContext.register(Application.class);
        applicationContext.setServletContext(servletContext);

        ServletRegistration.Dynamic servlet =
                servletContext.addServlet("dispatcher",
                        new DispatcherServlet(applicationContext));

        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }

    @Bean
    public DataSource dataSource(
            @Value("${datasource.dbname}") String dbname,
            @Value("${datasource.script}") String script) {

        return new EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.H2)
                .setName(dbname)
                .addScript(script)
                .build();
    }

//    // The web server is a simple standalone HTTP server that
//    // implements the H2 Console application.  localhost:8082
//    @Bean(initMethod = "start", destroyMethod = "stop")
//    public Server h2Server() throws SQLException {
//        return Server.createWebServer();
//    }
}
Open http://localhost:8080/console and connect to the jdbc:h2:mem:users database.
H2 database example login
H2 database example
Privacy policy
Back to Top