์๋ฒ ์คํ ์ DB Table ์์ฑ
์๋ฒ ์คํ ์ DB Table ์์ฑ
ApplicationRunner์ ๊ตฌํํ๋ ๊ฐ์ฒด๋ฅผ ๋ง๋ค์ด์ ์๋ฒ ์คํ ์ DB Table์ ์์ฑํด๋ณด์.
DatabaseConfig
config ํจํค์ง๋ฅผ ๋ง๋ค๊ณ DatabaseConfig๋ฅผ ๋ค์๊ณผ ๊ฐ์ด ์์ฑํด ์ฃผ์.
import lombok.RequiredArgsConstructor;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
@RequiredArgsConstructor
@Component
public class DatabaseConfig implements ApplicationRunner {
private final DataSource dataSource;
@Override
public void run(ApplicationArguments args) throws SQLException {
try(Connection connection = dataSource.getConnection()){
String sql = "create table if not exists users(" +
"id bigint(5) not null auto_increment," +
"email varchar(100) not null," +
"password varchar(100) not null," +
"primary key(id));";
Statement statement = connection.createStatement();
statement.executeUpdate(sql);
} catch (Exception e){
System.out.println(e);
}
}
}
DataSource
JDBC๋ก ๋ฐ์ดํฐ๋ฅผ ์ ๊ทผํ๋ Connection์ ๊ด๋ฆฌํ๋ ๊ฐ์ฒด์ด๋ค.
DataSource๋ฅผ ์ด์ฉํ๋ฉด ๋ฏธ๋ฆฌ ์์ฑ๋ Connection์ ์ ๊ณต๋ฐ์ ์ ์์ผ๋ฏ๋ก DB์ ๋ ํจ์จ์ ์ด๊ณ ๋น ๋ฅด๊ฒ ์ ๊ทผ์ด ๊ฐ๋ฅํ๋ค.
final๋ก ์ ์ธํ๊ณ ๋กฌ๋ณต์ @RequiredArgsConstructor
๋ฅผ ์ด์ฉํด Setter ์ฃผ์
์ผ๋ก ์ฌ์ฉํ๋ค.
ApplicationRunner
'ApplicationRunner'์ run()
๋ฉ์๋๋ ์ ํ๋ฆฌ์ผ์ด์
๊ตฌ๋ ์ ๋ฐ๋ก ์คํ๋๋ค.
DB ์ฐ๊ฒฐ ํ ํ ์ด๋ธ ์์ฑ
run()
๋ฉ์๋ ์์ ๋ด์ฉ์ sql ๋ฌธ์ ์ด์ฉํด ์์ Table์ ์์ฑํ๋ ๋ด์ฉ์ด๋ค.
DB Table
์๋ฒ ์คํ๊ณผ ๋์์ ์๋์ ํ
์ด๋ธ์ด ์์ฑ๋ ๊ฒ์ ํ์ธํ ์ ์๋ค.