1+ package com .baeldung .h2db .demo ;
2+
3+ import java .sql .ResultSet ;
4+ import java .sql .SQLException ;
5+ import java .util .Arrays ;
6+ import javax .annotation .PostConstruct ;
7+ import org .h2 .tools .Server ;
8+ import org .springframework .beans .factory .annotation .Autowired ;
9+ import org .springframework .boot .SpringApplication ;
10+ import org .springframework .boot .autoconfigure .SpringBootApplication ;
11+ import org .springframework .context .annotation .Bean ;
12+ import org .springframework .jdbc .core .JdbcTemplate ;
13+ import org .springframework .jdbc .core .RowMapper ;
14+
15+ @ SpringBootApplication
16+ public class SpringBootApp {
17+
18+ @ Autowired
19+ private JdbcTemplate jdbcTemplate ;
20+
21+ public static void main (String [] args ) {
22+ SpringApplication .run (SpringBootApp .class , args );
23+ }
24+
25+ @ PostConstruct
26+ private void initDb () {
27+ System .out .println (String .format (
28+ "****** Creating table: %s, and Inserting test data ******" , "Employees" ));
29+
30+ String sqlStatements [] = {
31+ "drop table employees if exists" ,
32+ "create table employees(id serial,first_name varchar(255),last_name varchar(255))" ,
33+ "insert into employees(first_name, last_name) values('Eugen','Paraschiv')" ,
34+ "insert into employees(first_name, last_name) values('Scott','Tiger')"
35+ };
36+
37+ Arrays .asList (sqlStatements ).stream ().forEach (sql -> {
38+ System .out .println (sql );
39+ jdbcTemplate .execute (sql );
40+ });
41+
42+ System .out .println (String .format ("****** Fetching from table: %s ******" , "Employees" ));
43+ jdbcTemplate .query ("select id,first_name,last_name from employees" ,
44+ new RowMapper <Object >() {
45+ @ Override
46+ public Object mapRow (ResultSet rs , int i ) throws SQLException {
47+ System .out .println (String .format ("id:%s,first_name:%s,last_name:%s" ,
48+ rs .getString ("id" ),
49+ rs .getString ("first_name" ),
50+ rs .getString ("last_name" )));
51+ return null ;
52+ }
53+ });
54+ }
55+
56+ @ Bean (initMethod = "start" , destroyMethod = "stop" )
57+ public Server inMemoryH2DatabaseServer () throws SQLException {
58+ return Server .createTcpServer ("-tcp" , "-tcpAllowOthers" , "-tcpPort" , "9091" );
59+ }
60+ }
0 commit comments