[JAVA] MVC

6 minute read


JAVA - MVC


JAVA MVC 패턴 구현 계획

  • DB Connection Class (DB Connection) :
  • Data 객체 (VO/DTO)
  • CRUD 처리 객체 (DAO)
  • Main Class
//======
// MVC
//======

// 1) DB Connection Class (DB Connection) :
	// 1) JDBC 드라이버 로드	
	// 2) Database Connection 연결
	// 6 Database Connection 해제

// 2) Data 객체 (VO/DTO) : 
	ex) Emp Class
		맴버 필드
            private int empno;
            private String ename;
            private String job;
            private int mgr;
            private String hiredate;
            private int sal;
            private int comm;
            private int deptno;

		맴버 생성자
            EmpVO() {}
            EmpVO(int empno, String ename, String job, int mgr, 
                         String hiredate, int sal, int comm, int deptno)

		맴버 메소드
            int getEmpno() {} String getEname() {} String getJob() {}
            int getMgr() {} String getHiredate() {} int getSal() {} 
            int getComm() {} int getDeptno() {}

3) CRUD 처리 객체 (DAO):
	ex) Dept CRUD Class

	// 3) Statement 생성
	// 4) SQL 전송 (executeQuery(), exectueUpdate())
	// 5) Result set(Sql 결과) 받기

	selectEmp(){}
	insertEmp(){}
	updateEmp(){}
	deleteEmp(){}
	listEmp(){}

//------
// 실행
//------
4) Main 기반 Class

main(){
	// 사원 관리 시스템

	while(){
		1. 사원 검색
		2. 사원 추가
		3. 사원 정보수정
		4. 사원 삭제
		5. 전체 사원 조회
		6. 시스템 종료
	}
	// 사원 관리 시스템 종료
}

DB Connection Class (DB Connection)

import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;

public class DBconn {
	
	public static Connection getConnection () {
		String jdbcDriver = "com.mysql.cj.jdbc.Driver";
		String jdbcUrl = "jdbc:mysql://localhost:3306/empDB?serverTimezone=UTC";
		String dbUser = "root";
		String dbPwd = "1234";
		Connection conn = null;
		
		try {
			Class.forName(jdbcDriver);
			conn = DriverManager.getConnection(jdbcUrl, dbUser, dbPwd);
			if (conn == null) {System.out.println("연결 실패");}
			else {System.out.println("연결 성공");}
			}
		catch (ClassNotFoundException ce){
			ce.printStackTrace();
		}
		catch (SQLException se) {
			se.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		return conn;
	}
}

Data 객체 (VO/DTO)

public class EmpVO {
	// member field
	private int empno;
	private String ename;
	private String job;
	private int mgr;
	private String hiredate;
	private int sal;
	private int comm;
	private int deptno;
	
	// constructor
	public EmpVO() {}
	public EmpVO(int empno, String ename, String job, int mgr, 
				 String hiredate, int sal, int comm, int deptno) {
		this.empno = empno; this.ename = ename; this.job = job; this.mgr = mgr;
		this.hiredate = hiredate; this.sal = sal; this.comm = comm; this.deptno = deptno;
	}
	
	// getter method
	public int getEmpno() {return empno;}
	public String getEname() {return ename;}
	public String getJob() {return job;}
	public int getMgr() {return mgr;}
	public String getHiredate() {return hiredate;}
	public int getSal() {return sal;}
	public int getComm() {return comm;}
	public int getDeptno() {return deptno;}

	@Override
	public String toString() {
		return "[ " + empno + " | " + ename + " | " + job + " | " + mgr + " |" + 
				hiredate + " | " + sal + " | " + comm + " | " + deptno + " ]";
	}	
}

CRUD 처리 객체 (DAO)

import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Connection;
import java.util.List;
import java.util.ArrayList;

public class EmpDAO {
	
    // DAO singleton
	public static EmpDAO dao = new EmpDAO();
	
	private EmpDAO() {};
	
	public static EmpDAO getInstance() {
			return dao;
	}
	
    // Read
	EmpVO selectEmp(int empno, Connection conn){
		
		EmpVO emp = null;
	
		try {
			String sqlSelect = "SELECT * \n" + 
							   "FROM emp4 \n" + 
							   "WHERE (empno = ?)";
			PreparedStatement pstmt = conn.prepareStatement(sqlSelect);
			pstmt.setInt(1, empno);
			
			ResultSet rs = pstmt.executeQuery();
			while(rs.next()) {
				emp = new EmpVO(rs.getInt("empno"), 
								rs.getString("ename"),
								rs.getString("job"),
								rs.getInt("mgr"),
								rs.getString("hiredate"),
								rs.getInt("sal"),
								rs.getInt("comm"),
								rs.getInt("deptno"));
							}
			pstmt.close();
				}
		catch (Exception e){
			System.out.println("selectEmp Error");
		}
		return emp;
	}
	
    // Create
	int insertEmp(EmpVO emp, Connection conn){
		
		int resultValue = 0;
		
		try {
			String sqlInsert = "INSERT INTO emp4 VALUES(?,?,?,?,?,?,?,?)";
			PreparedStatement pstmt = conn.prepareStatement(sqlInsert);
			pstmt.setInt(1, emp.getEmpno());
			pstmt.setString(2, emp.getEname());
			pstmt.setString(3, emp.getJob());
			pstmt.setInt(4, emp.getMgr());
			pstmt.setString(5, emp.getHiredate());
			pstmt.setInt(6, emp.getSal());
			pstmt.setInt(7, emp.getComm());
			pstmt.setInt(8, emp.getDeptno());
		
		resultValue = pstmt.executeUpdate();
		pstmt.close();
				}
		catch (Exception e){
			System.out.println("insertEmp Error");
		}
		return resultValue;
	}
	
    // Update
	int updateEmp(EmpVO emp, Connection conn) {
		
		int resultValue = 0;
		
		try {
			String sqlUpdate = "UPDATE emp4 \n" +
					 		   "SET sal = ? \n" +
					 		   "WHERE (empno = ?)";
			PreparedStatement pstmt = conn.prepareStatement(sqlUpdate);
			pstmt.setInt(1, emp.getSal());
			pstmt.setInt(2, emp.getEmpno());

			resultValue = pstmt.executeUpdate();
			pstmt.close();
		}
		catch (Exception e) {
			System.out.println("updateEmp Error");
		}
		return resultValue;
	}
	
    // Delete
	int deleteEmp(int empno, Connection conn) {
		
		int resultValue = 0;
		try {
			String sqlDelete = "DELETE FROM emp4 \n" +
							   "WHERE (empno = ?)";
			PreparedStatement pstmt = conn.prepareStatement(sqlDelete);
			pstmt.setInt(1, empno);

			resultValue = pstmt.executeUpdate();
			pstmt.close();
		}
		catch (Exception e) {
			System.out.println("deleteEmp Error");
		}
		return resultValue;
	}
	
    // Read (All)
	List<EmpVO> listEmp(Connection conn){
		
		List<EmpVO> empList = new ArrayList<>();

		try {
			String sqlSelectAll = "SELECT * \n" +
								  "FROM emp4";
			PreparedStatement stmt = conn.prepareStatement(sqlSelectAll);
			ResultSet rs = stmt.executeQuery();
			
			while(rs.next()) {
				empList.add(new EmpVO(
							rs.getInt("empno"), 
							rs.getString("ename"),
							rs.getString("job"),
							rs.getInt("mgr"),
							rs.getString("hiredate"),
							rs.getInt("sal"),
							rs.getInt("comm"),
							rs.getInt("deptno")));
			}
			stmt.close();
		}
		catch (Exception e) {
			System.out.println("listEmp Error");
		}	
		return empList;
	}
}

Main Class

import java.sql.Connection;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;

public class EmpMain {

	static EmpDAO eDao = EmpDAO.getInstance();
	
	static void selectE(int empno, Connection conn) {
		EmpVO emp = eDao.selectEmp(empno, conn);
		System.out.println(emp.toString());
	}
	
	static void insertE(EmpVO emp, Connection conn) {
		int resultValue = eDao.insertEmp(emp, conn);
		if (resultValue != 1) {System.out.println("데이터 정상적으로 추가 안됨");}
		else {System.out.println("데이터 정상적으로 추가됨");}
	}

	static void updateE(EmpVO emp, Connection conn) {
		int resultValue = eDao.updateEmp(emp, conn);
		if (resultValue != 1) {System.out.println("데이터 정상적으로 수정 안됨");}
		else {System.out.println("데이터 정상적으로 수정됨");}
	}

	static void deleteE(int empno, Connection conn) {
		int resultValue = eDao.deleteEmp(empno, conn);
		if (resultValue != 1) {System.out.println("데이터 정상적으로 삭제 안됨");}
		else {System.out.println("데이터 정상적으로 삭제됨");}		
	}
	
	static void listEmp(Connection conn) {
		List<EmpVO> empList = eDao.listEmp(conn);
		for (EmpVO emp : empList) {
			System.out.println(emp.toString());
		}
	}

    
	public static void main(String[] args) {
		
		System.out.println("==============================");
		System.out.println("------ 사원 관리 시스템 시작 ------");
		System.out.println("==============================");
		Scanner sc = new Scanner(System.in);
		
			try {
				Connection conn = DBconn.getConnection();
				int empno = 0; String ename = null; String job = null; int mgr = 0; 
				String hiredate = null; int sal = 0; int comm = 0; int deptno = 0;
				EmpVO emp = new EmpVO();
				
				while (true) {
				System.out.println("==== 1. 사원 검색 | 2. 사원 추가 | 3. 사원 정보수정 | 4. 사원 삭제 | 5. 전체 사원 조희 | 6. 시스템 종료 ====");
				System.out.println("희망하는 서비스에 해당하는 번호를 입력해주세요 => ");
				
				int choiceNum = sc.nextInt();
				switch (choiceNum) {
					case 1:
						System.out.println("========== [1. 검색] ==========");
						System.out.println("검색할 사원의 사원번호를 입력하세요 =>");
						empno = sc.nextInt();
		
						try {
							selectE(empno, conn);
						} catch (Exception e) {
							System.out.println("입력한 사원번호에 해당하는 사원이 존재하지 않습니다.");
						}
						break;
						
					case 2:
						System.out.println("========== [2. 추가] ==========");
						System.out.println("새롭게 추가할 사원의 사원번호를 입력하세요 예) 7000 =>"); empno = sc.nextInt(); 
						System.out.println("새롭게 추가할 사원의 이름을 입력하세요 예) 홍길동 =>"); ename = sc.next(); 
						System.out.println("새롭게 추가할 사원의 직무를 입력하세요 예) CLERK =>"); job = sc.next(); 
						System.out.println("새롭게 추가할 사원의 상사의 사원번호를 입력하세요 예) 8000 =>"); mgr = sc.nextInt(); 
						System.out.println("새롭게 입력할 사원의 입사일을 입력하세요 예) 2000-01-01 =>"); hiredate = sc.next(); 
						System.out.println("새롭게 추가할 사원의 급여를 입력하세요 예) 800 =>"); sal = sc.nextInt();
						System.out.println("새롭게 추가할 사원의 commission을 입력하세요 예) 0 =>"); comm = sc.nextInt();
						System.out.println("새롭게 추가할 사원의 부서번호를 입력하세요 예) 10 =>"); deptno = sc.nextInt();
						emp = new EmpVO(empno, ename, job, mgr, hiredate, sal, comm, deptno);
						
						insertE(emp, conn);
						break;
						
					case 3:
						System.out.println("========== [3. 수정] ==========");
						System.out.println("수정할 사원의 사원번호를 입력하세요 =>"); empno = sc.nextInt();
						System.out.println("수정할 사원의 급여를 입력하세요 =>"); sal = sc.nextInt();
						
						emp = new EmpVO(empno, ename, job, mgr, hiredate, sal, comm, deptno);
						updateE(emp, conn);
						break;
						
					case 4:
						System.out.println("========== [4. 삭제] ==========");
						System.out.println("삭제할 사원의 사원번호를 입력하세요 =>"); empno = sc.nextInt();
						
						deleteE(empno, conn);
						break;
						
					case 5:
						System.out.println("========== [5. 전체 조회] ==========");
						listEmp(conn);
						break;
						
					case 6:
						System.out.println("========== [6. 시스템 종료] ==========");
						conn.close();
						return;
					default:
						System.out.println("1번부터 6번 사이의 숫자를 입력해주세요");
					}
				}
			}
			catch (Exception e) {
				System.out.println("==시스템 문제 발생==");
			}
		sc.close();
	}

}