사이먼's 코딩노트
[Java] 호텔 예약 관리 프로그램 제작(11) 본문
[호텔 예약 관리 프로그램 제작]
- 작성된 모든 코드는 저의 깃허브 리포지터리에서 확인하실 수 있습니다.
- 깃허브 리포지터리 주소 : https://github.com/psm817/hotel_booking_proj
GitHub - psm817/hotel_booking_proj
Contribute to psm817/hotel_booking_proj development by creating an account on GitHub.
github.com
[mysql, lombok 추가]
- 프로그램 내에서 mysql와 lombok을 사용하기 위해서 build.gradle 파일에 각 라이브러리의 주소를 추가해야한다.
- mysql은 DBMS으로 데이터베이스 관리 시스템이다.
- 각 Dao에서 List을 조회하거나 데이터를 추가, 삭제하는 기능을 DB와 연결해서 진행할 예정이기 때문에 mysql을 사용해야한다.
- lombok은 어노테이션 기반으로 코드를 자동 완성 해주는 라이브러리이다.
- lombok을 사용하면 Getter, Setter 등과 같이 다양한 방면의 코드를 자동 완성시킬 수 있다.
- 프로그램에서 고유 번호인 id에 대해서 가져오고 불러오고 하는 코드를 직접 작성하기 않고 lombok 라이브러리를 통해 getId나 setId를 사용할 예정이다.
dependencies {
testImplementation platform('org.junit:junit-bom:5.9.1')
testImplementation 'org.junit.jupiter:junit-jupiter'
// https://mvnrepository.com/artifact/mysql/mysql-connector-java
implementation 'mysql:mysql-connector-java:8.0.22'
// https://mvnrepository.com/artifact/org.projectlombok/lombok
compileOnly 'org.projectlombok:lombok:1.18.32'
}
- build.gradle 파일에서 dependencies 안에 해당 라이브러리의 주소를 적어주면 된다.
- 각 라이브러리의 주소는 구글에 maven repository를 검색하면 홈페이지에 들어가서 검색할 수 있다.
[DBConnection 추가 및 DB 세팅]
- 이제는 구현된 프로그램에 List 배열을 통한 로컬 데이터가 아닌 DB를 통한 데이터를 조회, 삽입, 삭제하기 위해 DBConnection을 추가해봅시다.
- 작성된 코드는 db라는 패키지를 따로 생성하여 DBConnection.java 클래스에 코드를 추가하였다.
package org.example.db;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DBConnection {
private Connection connection;
public static String DB_NAME;
public static String DB_USER;
public static String DB_PASSWORD;
public static int DB_PORT;
public void connect() {
String url = "jdbc:mysql://localhost:" + DB_PORT + "/" + DB_NAME
+ "?serverTimezone=Asia/Seoul&useOldAliasMetadataBehavior=true";
String user = DB_USER;
String password = DB_PASSWORD;
String driverName = "com.mysql.cj.jdbc.Driver";
try {
connection = DriverManager.getConnection(url, user, password);
Class.forName(driverName);
} catch (SQLException e) {
System.err.printf("[SQL 예외] : %s\n", e.getMessage());
} catch (ClassNotFoundException e) {
System.err.printf("[드라이버 클래스 로딩 예외] : %s\n", e.getMessage());
}
}
public int selectRowIntValue(String sql) {
Map<String, Object> row = selectRow(sql);
for(String key : row.keySet()) {
return (int) row.get(key);
}
return -1;
}
public String selectRowStringValue(String sql) {
Map<String, Object> row = selectRow(sql);
for(String key : row.keySet()) {
return (String) row.get(key);
}
return "";
}
public Boolean selectRowBooleanValue(String sql) {
Map<String, Object> row = selectRow(sql);
for(String key : row.keySet()) {
if(row.get(key) instanceof String) {
return ((String) row.get(key)).equals("1");
}
else if(row.get(key) instanceof Integer) {
return ((int) row.get(key)) == 1;
}
else if(row.get(key) instanceof Boolean) {
return ((boolean) row.get(key));
}
}
return false;
}
public Map<String, Object> selectRow(String sql) {
List<Map<String, Object>> rows = selectRows(sql);
if(rows.size() == 0) {
return new HashMap<String, Object>();
}
return rows.get(0);
}
public List<Map<String, Object>> selectRows(String sql) {
List<Map<String, Object>> rows = new ArrayList<>();
try {
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData metaData = rs.getMetaData();
int columnSize = metaData.getColumnCount();
while(rs.next()) {
Map<String, Object> row = new HashMap<>();
for(int columnIndex = 0; columnIndex < columnSize; columnIndex++) {
String columnName = metaData.getColumnName(columnIndex + 1);
Object value = rs.getObject(columnName);
if(value instanceof Long) {
int numValue = (int) (long) value;
row.put(columnName, numValue);
}
else if(value instanceof Timestamp) {
String dateValue = value.toString();
dateValue = dateValue.substring(0, dateValue.length() - 2);
row.put(columnName, dateValue);
}
else {
row.put(columnName, value);
}
}
rows.add(row);
}
} catch (SQLException e) {
System.err.printf("[SQL 예외, SQL : %s] : %s\n", sql, e.getMessage());
e.printStackTrace();
}
return rows;
}
public int delete(String sql) {
int affectedRows = 0;
Statement stmt;
try {
stmt = connection.createStatement();
affectedRows = stmt.executeUpdate(sql);
} catch (SQLException e) {
System.err.printf("[SQL 예외, SQL : %s] : %s\n", sql, e.getMessage());
}
return affectedRows;
}
public int update(String sql) {
int affectedRows = 0;
Statement stmt;
try {
stmt = connection.createStatement();
affectedRows = stmt.executeUpdate(sql);
} catch (SQLException e) {
System.err.printf("[SQL 예외, SQL : %s] : %s\n", sql, e.getMessage());
}
return affectedRows;
}
public int insert(String sql) {
int id = -1;
try {
Statement stmt = connection.createStatement();
stmt.execute(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
if(rs.next()) {
id = rs.getInt(1);
}
} catch (SQLException e) {
System.err.printf("[SQL 예외, SQL : %s] : %s\n", sql, e.getMessage());
}
return id;
}
public void close() {
if(connection != null) {
try {
connection.close();
} catch (SQLException e) {
System.err.printf("[SQL 예외] : %s\n", e.getMessage());
}
}
}
}
- DBConnection.java 클래스에 있는 코드는 SELECT, INSERT, UPDATE, DELETE 등을 위한 하나의 유틸로 생각해두면 좋다.
- DB가 연결되기 위해서는 코드 상단의 connect() 메서드를 보면 알 수 있듯이 DB_PORT, DB_NAME, DB_USER, DB_PASSWORD의 기본 정보가 필요하다.
- DBConnection도 마찬가지로 Container에 객체 변수를 선언하고, 어디서든 호출해서 사용할 수 있도록 해준다.
package org.example.container;
import org.example.controller.Session;
import org.example.dao.BookingDao;
import org.example.dao.GuestDao;
import org.example.dao.RoomDao;
import org.example.db.DBConnection;
import org.example.service.BookingService;
import org.example.service.GuestService;
import org.example.service.RoomService;
public class Container {
public static Session session;
public static DBConnection dbConnection;
public static BookingDao bookingDao;
public static RoomDao roomDao;
public static GuestDao guestDao;
public static BookingService bookingService;
public static RoomService roomService;
public static GuestService guestService;
static {
bookingDao = new BookingDao();
roomDao = new RoomDao();
guestDao = new GuestDao();
bookingService = new BookingService();
roomService = new RoomService();
guestService = new GuestService();
}
public static DBConnection getDBConnection() {
if(dbConnection == null) {
dbConnection = new DBConnection();
}
return dbConnection;
}
public static Session getSession() {
if(session == null) {
session = new Session();
}
return session;
}
}
- session과 동일하게 dbConnection도 마찬가지로 생성자를 통해 바로 연결이 되지 않고, 조건문을 사용해서 연결이 되어있지 않다면 즉, null이라면 DBConnection 객체를 생성하도록 한다.
- 마지막으로 App에서 프로그램 실행과 동시에 DB와 연결이 될 수 있도록 DB 기본 정보를 세팅하고 DBConnection 객체를 생성하도록 한다.
- 아래 코드는 중간에 작성된 코드를 모두 삭제하고 DBConnection에 관련된 코드만 있다는 점, 참고 부탁드립니다.
package org.example;
import org.example.container.Container;
import org.example.controller.*;
import org.example.db.DBConnection;
import org.example.util.Util;
import java.util.Scanner;
public class App {
public App() {
DBConnection.DB_NAME = "hotel_proj";
DBConnection.DB_USER = "sbsst";
DBConnection.DB_PASSWORD = "sbs123414";
DBConnection.DB_PORT = 3306;
Container.getDBConnection().connect();
}
public void start() {
sc.close();
Container.getDBConnection().close();
System.out.println("감사합니다. 다음에 또 방문해주세요.");
}
}
- 호텔 예약 프로그램의 DB 정보는 작성된 코드에서도 알 수 있듯이, DB_NAME은 "hotel_proj", DB_USER는 "sbsst", DB_PASSWORD는 "sbs123414", DB_PORT는 3306이다.
- DB_PORT는 사용자가 임의로 포트번호를 변경하지 않는 이상 기본 포트번호는 3306이다.
- DBConnection을 App 상단에서 연결해줬다면 가장 하단에서 반드시 DB 연결을 끊어주는 close() 메서드를 호출해야한다.
반응형
'프로젝트 > [Java] 호텔 예약 관리 프로그램 제작' 카테고리의 다른 글
[Java] 호텔 예약 관리 프로그램 제작(13) (0) | 2024.04.18 |
---|---|
[Java] 호텔 예약 관리 프로그램 제작(12) (0) | 2024.04.17 |
[Java] 호텔 예약 관리 프로그램 제작(10) (0) | 2024.04.17 |
[Java] 호텔 예약 관리 프로그램 제작(9) (0) | 2024.04.17 |
[Java] 호텔 예약 관리 프로그램 제작(8) (0) | 2024.04.17 |