Spring/Toby의 스프링3 따라하기
JdbcTemplate정리, Hikari Pool과 연동
KyeongRok Kim
2021. 11. 24. 15:53
DDL
Create Table
employee라는 이름의 테이블을 만듭니다.
컬럼은 id, name, contents 3개 입니다.
if not exists 가 들어있어서 없을때만 create table을 실행하고 테이블이 존재한다면 실행하지 않습니다.
.update()를 썼기 때문에 리턴값이 0입니다.
public int createTable() {
// table이 있는지 먼저 check
return this.jdbcTemplate.update(String.format("create table if not exists employee(id bigint, name varchar, contents text)"));
}
With Primary Key
public int createTable() {
// table이 있는지 먼저 check
return this.jdbcTemplate.update(String.format("create table if not exists " +
"customer_service_record(id bigint, car_model_id int, cs_start_date timestamp," +
" contents text, PRIMARY KEY (id))"));
}
Drop Table
테이블을 지우고 싶을 때 씁니다.
public void dropTable() {
// table이 있는지 먼저 check
this.jdbcTemplate.execute("drop table if exists employee");
}
build.gradle에 추가할 Hikari cp
implementation 'com.zaxxer:HikariCP:5.0.0'
Hikari DataSource 만들기
public DataSource dataSourceHikari() {
HikariConfig hc = new HikariConfig();
hc.setDriverClassName("org.postgresql.Driver");
hc.setJdbcUrl("jdbc:postgresql://<ip>:9999/testdb");
hc.setUsername("postgres");
hc.setPassword("<pw>");
DataSource dataSource = new HikariDataSource(hc);
return dataSource;
}
JdbcTemplate과 연동
@Bean
public AccountsDao accountsDao() {
return new AccountsDao(new JdbcTemplate(dataSourceHikari()));
}
728x90