<!-- for jdbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<!-- for migrations of table to db -->
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
Configuration for PostgreSQL
// FOR JDBCapp:datasource:main:driver-class-name:org.postgresql.Driverjdbc-url:jdbc:postgresql://[host]:[port]/[db name]username:[username]password:[password]pool-size:[poolsize]server:error:include-binding-errors:alwaysinclude-message:always
For flyway migration
If you are using Flyway for db migration, create a folder db/migrations inside resource folder
Name the migration V[number]__[name of migration].sql
Example : V1__InitTables.sql
Configuring HikariDataSource
@ConfigurationpublicclassDataSouceConfig{@Bean@Primary// to get the required environment variable from configuration@ConfigurationProperties(prefix="app.datasource.main")publicHikariDataSourcehikariDataSource(){returnDataSourceBuilder.create().type(HikariDataSource.class).build();}@BeanpublicJdbcTemplatejdbcTemplate(HikariDataSourcehikariDataSource){returnnewJdbcTemplate(hikariDataSource);}}
Queries
// select statementStringsql="SELECT * FROM table;";returnjdbcTemplate.query(sql,newTRowMapper());// insert statementStringsql="""insert into table (col1, col2) values (?, ?);""";returnjdbcTemplate.update(sql,value1,value2);// delete statementreturnjdbcTemplate.update("delete from table where id = ?",id);// with conditionStringsql="SELECT * FROM table where id = ?;";List<T>movies=jdbcTemplate.query(sql,newTRowMapper(),id);returnmovies.stream().findFirst();