SprintBoot part2 (2)
JDBC ์์ํ๊ธฐ
JDBC allows a java application to connect a relational database
ํฌ๊ฒ ๋ ๋จ๊ณ ๋ ์ด์ด๋ก ๊ตฌ์ฑ๋๋ค.
- JDBC API
- JDBS DB Driver
- docker๋ฅผ ์ด์ฉํด mysql ์คํ
- IntelliJ ์ฐ๊ฒฐ
- maven dependency ์ถ๊ฐ
JDBC CURD ์ค์ต
1. jdbc connection
public class JdbcCustomerRepository {
private static final Logger logger = LoggerFactory.getLogger(JdbcCustomerRepository.class);
public static void main(String[] args) throws SQLException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost/order_mgmt",id ,pw);
statement = connection.createStatement();
resultSet = statement.executeQuery("select * from customers");
while(resultSet.next()){
var name = resultSet.getString("name");
var customerId = UUID.nameUUIDFromBytes(resultSet.getBytes("customer_id"));
logger.info("customer id =>{} ,customer name =>{}",customerId,name);
}
} catch (SQLException e) {
logger.error("Got error while closing connection", e);
}finally {
try{
//connection์ ๋ฆฌ์์ค๊ฐ ์ปค์ ์ดํ๋ฆฌ์ผ์ด์
์ด๋ db ๋ถ๋ด์ด๋๋ ๊ผญ ์ฟผ๋ฆฌ์คํํ์ ๋ซ์์ค์ผํ๋ค.
if(connection != null) connection.close();
if(statement != null) statement.close();
if(resultSet != null) resultSet.close();
}catch (SQLException e){
logger.error("Got error while closing connection", e);
}
}
}
}
์์ธ์ฒ๋ฆฌ ๋๋ฌธ์ ์ฝ๋๊ฐ ๋๋ฌ์ด๋ฐ java 10์์ ์ด๊ฑธ ๋ณด์ํด์ฃผ๋ ๋ฐฉ์์ด ์๊น
⇒ Connection์ด AutoCloseable์ ์์๋ฐ์ ๋ธ๋ฝ์ด ๋๋ฌ์๋ ์๋์ผ๋ก ๋ซ์์ค๋ค.
public class JdbcCustomerRepository {
private static final Logger logger = LoggerFactory.getLogger(JdbcCustomerRepository.class);
public static void main(String[] args) throws SQLException {
try(
var connection = DriverManager.getConnection("jdbc:mysql://localhost/order_mgmt",id ,pw);
var statement = connection.createStatement();
var resultSet = statement.executeQuery("select * from customers");
) {
while(resultSet.next()){
var name = resultSet.getString("name");
var customerId = UUID.nameUUIDFromBytes(resultSet.getBytes("customer_id"));
logger.info("customer id =>{} ,customer name =>{}",customerId,name);
}
} catch (SQLException e) {
logger.error("Got error while closing connection", e);
}
}
}
2. select
public class JdbcCustomerRepository {
private static final Logger logger = LoggerFactory.getLogger(JdbcCustomerRepository.class);
public List<String> findNames(String name){
var SELECT_SQL = "select * from customers WHERE name ='%s'".formatted(name);
logger.info(SELECT_SQL);
List<String> names = new ArrayList<>();
try(
var connection = DriverManager.getConnection("jdbc:mysql://localhost/order_mgmt",id ,pw);
var statement = connection.createStatement();
var resultSet = statement.executeQuery(SELECT_SQL);
) {
while(resultSet.next()){
var customerName = resultSet.getString("name");
var customerId = UUID.nameUUIDFromBytes(resultSet.getBytes("customer_id"));
var createdAt = resultSet.getTimestamp("created_at").toLocalDateTime();
logger.info("customer id =>{}, customer name =>{}, createdAt ={}",customerId,name,createdAt);
names.add(name);
}
} catch (SQLException e) {
logger.error("Got error while closing connection", e);
}
return names;
}
public static void main(String[] args) throws SQLException {
var names = new JdbcCustomerRepository().findNames("tester01");
System.out.println(names);
}
}
SQL injecton
์์ ๊ฐ์ด SQL ๋ฌธ์์ด ์กฐํฉ์ ์ฌ์ฉํ์์๋, select์ or ์ ์ ์ฝ์ ํ์ฌ ์์น์์ ์ฟผ๋ฆฌ๋ฅผ ์คํํด ์ ๋ณด๋ฅผ ๋นผ๊ฐ๋ ๊ฒ๊ณผ ๊ฐ์ SQL injection์ด ๋ฐ์ํ ์์๋ค.
public static void main(String[] args) throws SQLException {
var names = new JdbcCustomerRepository().findNames("tester01' or 'a'='a");
System.out.println(names);
}
prepareStatement
sql ๋ฌธ์์ด ์กฐํฉ์ ์ ์คํ๊ฒ ์ฌ์ฉํ์ฌ์ผํ๊ณ ์ ์ปจํธ๋กค ํ ์ ์์ด์ผํ๋ค.
prepareStatement๋ฅผ ์ฌ์ฉํ๋ฉด ์ฟผ๋ฆฌ์ ๋ฌธ์ฅ์ ๋ถ์ํ๊ณ ์ปดํ์ผ, ์คํ ๊ณผ์ ์ ํ๋ฒ๋ง ๊ฑฐ์นํ ์บ์์ ๋ด๊ฒจ์ ์ฌ์ฌ์ฉ๋๋ค. ๋๋ฌธ์ ์ฟผ๋ฆฌ๋ฌธ์ด ๊ณ ์ ์ด ๋์ด์๊ธฐ ๋๋ฌธ์ ์ค๊ฐ์ ์ฟผ๋ฆฌ๋ฅผ ๋ณ๊ฒฝํ ์ ์๋ค.(๋ค์ด๋๋ฏน ์ฟผ๋ฆฌ๊ฐ ์๋จ) ๋ฟ๋ง ์๋๋ผ ์บ์์ฌ์ฉ์ผ๋ก ์ฑ๋ฅ์๋ ์ด์ ์ด ์๋ค.
public List<String> findNames(String name){
var SELECT_SQL = "select * from customers WHERE name = ?"; // ? ๋งํฌ ์ด์ฉ
logger.info(SELECT_SQL);
List<String> names = new ArrayList<>();
try(
ntatement = connection.prepareStatement(SELECT_SQL);
) {
// aoutoclose๊ฐ ๋๋๊ฒ ์๋๋ผ ๋ฐ์..????
statement.setString(1,name); // ์ธํ
์ค๋ 1๋ถํฐ
logger.info("statement =>{}",statement);
try(var resultSet = statement.executeQuery();){
while(resultSet.next()){
var customerName = resultSet.getString("name");
var customerId = UUID.nameUUIDFromBytes(resultSet.getBytes("customer_id"));
var createdAt = resultSet.getTimestamp("created_at").toLocalDateTime();
logger.info("customer id =>{}, customer name =>{}, createdAt ={}",customerId,name,createdAt);
names.add(customerName);
}
}
} catch (SQLException e) {
logger.error("Got error while closing connection", e);
}
return names;
}
⇒ SQL injection์ ์์ด ํจ์ฌ ์์ ํ ์ฝ๋๋ฅผ ์์ฑํ ์ ์๋ค.
3. CURD
public class JdbcCustomerRepository {
private static final Logger logger = LoggerFactory.getLogger(JdbcCustomerRepository.class);
private final String SELECT_ALL_SQL = "select * from customers";
private final String SELECT_BY_NAME_SQL = "select * from customers WHERE name = ?";
private final String INSERT_SQL = "INSERT INTO customers(customer_id,name,email) VALUES (UUID_TO_BIN(?),?,?)";
private final String UPDATE_BY_ID_SQL = "UPDATE customers SET name= ? WHERE customer_id = UUID_TO_BIN(?)";
private final String DELETE_ALL_SQL = "DELETE FROM customers";
public List<String> findALLNames(){
List<String> names = new ArrayList<>();
try(
var connection = DriverManager.getConnection("jdbc:mysql://localhost/order_mgmt",id ,pw);
var statement = connection.prepareStatement(SELECT_ALL_SQL);
var resultSet = statement.executeQuery();
) {
while(resultSet.next()){
var customerName = resultSet.getString("name");
var customerId = toUUID(resultSet.getBytes("customer_id"));
var createdAt = resultSet.getTimestamp("created_at").toLocalDateTime();
logger.info("customer id =>{}, customer name =>{}, createdAt ={}",customerId,customerName,createdAt);
names.add(customerName);
}
} catch (SQLException e) {
logger.error("Got error while closing connection", e);
}
return names;
}
public List<String> findByNames(String name){
List<String> names = new ArrayList<>();
try(
var connection = DriverManager.getConnection("jdbc:mysql://localhost/order_mgmt",id ,pw);
var statement = connection.prepareStatement(SELECT_BY_NAME_SQL);
) {
statement.setString(1,name); // ์ธํ
์ค๋ 1๋ถ
logger.info("statement =>{}",statement);
try(var resultSet = statement.executeQuery();){
while(resultSet.next()){
var customerName = resultSet.getString("name");
var customerId = toUUID(resultSet.getBytes("customer_id"));
var createdAt = resultSet.getTimestamp("created_at").toLocalDateTime();
logger.info("customer id =>{}, customer name =>{}, createdAt ={}",customerId,name,createdAt);
names.add(customerName);
}
}
} catch (SQLException e) {
logger.error("Got error while closing connection", e);
}
return names;
}
public int insertCustomer(UUID customerId, String name, String email){
try(
var connection = DriverManager.getConnection("jdbc:mysql://localhost/order_mgmt",id ,pw);
var statement = connection.prepareStatement(INSERT_SQL);
) {
statement.setBytes(1,customerId.toString().getBytes());
statement.setString(2,name);
statement.setString(3,email);
return statement.executeUpdate();
}
catch (SQLException e) {
logger.error("Got error while closing connection", e);
}
return 0;
}
public int updateCustomerName(String name, UUID customerId){
try(
var connection = DriverManager.getConnection("jdbc:mysql://localhost/order_mgmt",id ,pw);
var statement = connection.prepareStatement(UPDATE_BY_ID_SQL);
) {
statement.setString(1,name);
statement.setBytes(2,customerId.toString().getBytes());
logger.info("customer id =>{}, customer name =>{}",customerId,name);
return statement.executeUpdate();
}
catch (SQLException e) {
logger.error("Got error while closing connection", e);
}
return 0;
}
public int deleteAllCustomer(){
try(
var connection = DriverManager.getConnection("jdbc:mysql://localhost/order_mgmt",id ,pw);
var statement = connection.prepareStatement(DELETE_ALL_SQL);
) {
return statement.executeUpdate();
}
catch (SQLException e) {
logger.error("Got error while closing connection", e);
}
return 0;
}
static UUID toUUID(byte[] bytes){
var byteBuffer = ByteBuffer.wrap(bytes);
return new UUID(byteBuffer.getLong(),byteBuffer.getLong());
}
public static void main(String[] args) throws SQLException {
var customerRepository = new JdbcCustomerRepository();
var count = customerRepository.deleteAllCustomer();
logger.info("delete count => {}",count);
customerRepository.insertCustomer(UUID.randomUUID(), "new-user","new-user@gmail.com");
var customer2 = UUID.randomUUID();
customerRepository.insertCustomer(customer2, "new-user2","new-user2@gmail.com");
customerRepository.updateCustomerName("update-user",customer2);
var names = customerRepository.findALLNames();
System.out.println(names);
}
}
4. UUID
UUID type 4 : ํ์ ํต์ผํด์ ์ฌ์ฉํ๊ธฐ
static UUID toUUID(byte[] bytes){
var byteBuffer = ByteBuffer.wrap(bytes);
return new UUID(byteBuffer.getLong(),byteBuffer.getLong());
}
UUID customerId = toUUID(string.getBytes());
์ถ์ฒ - ํด๋ฆฌ : SpringBoot Part1
'Back-end ๋ฐ๋ธ์ฝ์ค > week 03 - 05 TIL (Spring)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[TIL] 221110 - SpringBoot Part2 : Embedded DB, Named Parameter Template, ํธ๋์ญ์ (0) | 2022.11.11 |
---|---|
[TIL] 221109 - SpringBoot Part2 : Spring์ JDBC์ง์ (0) | 2022.11.10 |
[TIL] 221107 - SpringBoot Part2 : Spring Test ์์ํ๊ธฐ (0) | 2022.11.08 |
[TIL] 221104 - SpringBoot Part1 : logging, SpringBoot (2) | 2022.11.06 |
[TIL] 221103 - SpringBoot Part1 - ์ ํ๋ฆฌ์ผ์ด์ ์์ฑ ๊ด๋ฆฌ (0) | 2022.11.06 |
๋๊ธ