PostgreSQLローカルdbをスプリングブートにバインドする


依存項目の追加

implementation group: 'org.postgresql', name: 'postgresql'
バージョン情報を指定しない場合、Spring Bootは自動的に最適化バージョンとして指定されます.

ファイルの設定

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/db명
    username: sloth
    password: 비밀번호
    driver-class-name: org.postgresql.Driver
postgresqlのデフォルトポートは5432です.

テストコード


example/PostgreSQLRunner
@Component
public class PostgresSQLRunner implements ApplicationRunner {
    @Autowired
    DataSource dataSource;

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        try (Connection connection = dataSource.getConnection()){
            System.out.println(dataSource.getClass());
            System.out.println(connection.getMetaData().getURL());
            System.out.println(connection.getMetaData().getUserName());

            Statement statement = connection.createStatement();
            String sql = "CREATE TABLE t_product(product_no INTEGER NOT NULL, product_name VARCHAR(255), PRIMARY KEY (product_no))";
            statement.executeUpdate(sql);
        }
        jdbcTemplate.execute("INSERT INTO t_product VALUES (1, 'Big shirt')");
    }
}
コンソールにデバイス情報を表示
jdbc:postgresql://localhost:5432/slothdb
sloth

データベースの確認



ローカルデバイスにバインドされています.
次はドックコンテナ