pom.xml 파일 의존성 추가
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
JAVA - DB 연동
JDBC 클래스 전체 구조
Package Import → JDBC Driver Load → Connection 객체(인스턴스) 생성 → Statement 객체 생성 → Query 실행 → ResultSet 객체로부터 데이터 추출 → ResultSet Close → Statement 객체 Clase → Connection 객체 Close
DBConnectionMgr.java 👈🏻 전 포스팅 참고
private Vector connections = new Vector(10);
private String _driver = "com.mysql.cj.jdbc.Driver",
_url = "jdbc:mysql://127.0.0.1:8080/example",
_user = "root",
_password = "@@@@;
private DBConnectionMgr pool ;
public UserInsert() {
pool = DBConnectionMgr.getInstance(); //Singleton
}
싱글톤 패턴(Singleton pattern)을 사용한다.
- new 연산자를 제한하기 위해 생성자의 접근 제한자는 항상 private으로 선언
- 유일한 단일 객체를 반환하기 위해 static method가 필요
- 유일한 단일 객체를 참조할 수 있는 static 참조 변수가 필요
DBConnectionMgr.java 👈🏻
private static DBConnectionMgr instance = null;
public static DBConnectionMgr getInstance() {
if (instance == null) {
synchronized (DBConnectionMgr.class) {
if (instance == null) {
instance = new DBConnectionMgr();
}
}
}
return instance;
}
public int saveUser(User user) {
int successCount = 0;
String sql = null;
Connection connection = null; // 전역변수로 빼줌
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
User user을 매개변수로 하는 public int saveUser 메서드를 생성
User user (command enter로 해당 메서드로 이동)
@Data
@Builder
//@AllArgsConstructor //builer pattern 필수
public class User {
private int userId;
private String username;
private String password;
private String name;
private String email;
User class는 빌더패턴으로 구현
추가적인 빌더 클래스를 구현
빌더의 생성 비용이 크지는 않지만, 성능이 민감할 경우 문제가 될 수도?!
롬복이란?

try { // why???
connection = pool.getConnection(); //workbench 에 접속
sql = "insert into user_mst\r\n"
+ "values (0,?,?,?,?)";
/*
* ? 쓰는 이유 : 어떤 값이 들어갈지 모르니
*
*/
private DBConnectionMgr pool(DBConnectionMgr클래스) 을 Connection 클래스 connection 객체에 대입 → MySQL workbench에 접속
sql = "insert into user_mst\r\n"
+ "values (0,?,?,?,?)";
MySQL에 insert into user_mst values (0,~) 기입하는거와 동일한 원리, 뒤에 0은 MySQL의 user_id AI(Auto increse) index 번호, ? 는 변수가 무엇으로 기입될지 모르기 때문