알고보면코딩천재

Service 본문

Java

Service

알코천 2022. 8. 17. 12:56

Dao 만들땐 쿼리만 잘 짜면 된다.

Service를 잘 만들어야 한다. (외부에 노출시키는 것)

서비스는 Dao를 조합시켜서 만든 것


커넥션 하나로 만들기 트랜잭션 관리 위해

 

각각의 conn들을 삭제한다 하나의 conn으로 만들어주기 위해.

 

다섯번 반복해서 해봐도 이해가 안되면 쌤한테 가기. 그러면 전원 술 사주신다고 함

package service;

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

public class DeptDao {
	
	private Connection conn;
	
	public DeptDao(Connection conn) {
		this.conn = conn;
	}
	
	public int 부서수정(String dname, String loc, int deptno) { 
		int result = -1;
		try {
			// 1.SQL 작성
			StringBuilder sql = new StringBuilder();
			sql.append("UPDATE dept SET dname = ?, loc = ? WHERE deptno = ?"); 
			
			
			
			// 3. 문장 완성
			PreparedStatement pstmt = conn.prepareStatement(sql.toString());
			// 물음표 번호는 1부터 시작!!
			pstmt.setString(1, dname);
			pstmt.setString(2, loc);
			pstmt.setInt(3, deptno);

			
			// 4. 문장 전송
			result = pstmt.executeUpdate(); // 문장전송, commit
		
			
			// result = 1 행 하나 변경, 0 변경 안됨, -1 오류
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public int 부서삭제(int deptno) { 
		int result = -1;
		try {
			// 1.SQL 작성
			StringBuilder sql = new StringBuilder();
			sql.append("DELETE FROM dept WHERE deptno = ?"); 
			
			
			
			// 3. 문장 완성
			PreparedStatement pstmt = conn.prepareStatement(sql.toString());
			// 물음표 번호는 1부터 시작!!
			pstmt.setInt(1, deptno);

			
			// 4. 문장 전송
			result = pstmt.executeUpdate(); // 문장전송, commit
		
			
			// result = 1 행 하나 변경, 0 변경 안됨, -1 오류
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public int 부서추가(Dept dept) {
		int result = -1;

		try {
			StringBuilder sql = new StringBuilder();
			sql.append("INSERT INTO dept ");
			sql.append("VALUES(?,?,?)");

		

			PreparedStatement pstmt = conn.prepareStatement(sql.toString());

			pstmt.setInt(1, dept.getDeptno());
			pstmt.setString(2, dept.getDname());
			pstmt.setString(3, dept.getLoc());

			result = pstmt.executeUpdate();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	} // end of 부서추가

	public Dept 부서한건보기(int deptno) {

		Dept dept = new Dept();

		try {
			
			PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM dept WHERE deptno = ?" );
			ResultSet rs = pstmt.executeQuery();
			if (rs.next()) {

				dept.setDeptno(rs.getInt("deptno"));
				dept.setDname(rs.getString("dname"));
				dept.setLoc(rs.getString("loc"));

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return dept;
	} // end of 부서한건보기

	public ArrayList<Dept> 부서목록보기() {
		ArrayList<Dept> depts = new ArrayList<>();

		try {
		
			PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM dept");
			ResultSet rs = pstmt.executeQuery();
			while (rs.next()) {
				Dept dept = new Dept();
				dept.setDeptno(rs.getInt("deptno"));
				dept.setDname(rs.getString("dname"));
				dept.setLoc(rs.getString("loc"));

				depts.add(dept);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return depts;
	} // end of 부서목록보기

}
package service;

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

// Data, Access, Object
public class EmpDao {
	
	private Connection conn;
	
	public EmpDao(Connection conn) {
		this.conn = conn;
	}
	
	public int 직원수정(int empno, int deptno) { 
		int result = -1;
		try {
			// 1.SQL 작성
			StringBuilder sql = new StringBuilder();
			sql.append("UPDATE emp SET deptno = ? WHERE empno = ?"); 
			
		
			
			// 3. 문장 완성
			PreparedStatement pstmt = conn.prepareStatement(sql.toString());
			// 물음표 번호는 1부터 시작!!
			pstmt.setInt(1, deptno);
			pstmt.setInt(2, empno);

			
			// 4. 문장 전송
			result = pstmt.executeUpdate(); // 문장전송, commit
		
			
			// result = 1 행 하나 변경, 0 변경 안됨, -1 오류
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	
	
	public int 직원삭제(int empno) { 
		int result = -1;
		try {
			// 1.SQL 작성
			StringBuilder sql = new StringBuilder();
			sql.append("DELETE FROM EMP WHERE empno = ?"); 
			
		
			
			// 3. 문장 완성
			PreparedStatement pstmt = conn.prepareStatement(sql.toString());
			// 물음표 번호는 1부터 시작!!
			pstmt.setInt(1, empno);

			
			// 4. 문장 전송
			result = pstmt.executeUpdate(); // 문장전송, commit
		
			
			// result = 1 행 하나 변경, 0 변경 안됨, -1 오류
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	
	public int 직원추가(Emp emp) {
		int result = -1;
		try {
			// 1.SQL 작성
			StringBuilder sql = new StringBuilder();
			sql.append("INSERT INTO emp "); // 띄어쓰기 꼭 해줘야한다
			sql.append("VALUES(?,?,?,?,sysdate,?,?,?)"); 
			
		
			
			// 3. 문장 완성
			PreparedStatement pstmt = conn.prepareStatement(sql.toString());
			// 물음표 번호는 1부터 시작!!
			pstmt.setInt(1, emp.getEmpno());
			pstmt.setString(2, emp.getEname());
			pstmt.setString(3, emp.getJob());
			pstmt.setInt(4, emp.getMgr());
			pstmt.setInt(5, emp.getSal());
			pstmt.setInt(6, emp.getComm());
			pstmt.setInt(7, emp.getDeptno());
			
			// 4. 문장 전송
			result = pstmt.executeUpdate(); // 문장전송, commit
		
			
			// result = 1 행 하나 변경, 0 변경 안됨, -1 오류
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public ArrayList<Emp> 직원목록보기() {
		ArrayList<Emp> emps = new ArrayList<>();

		try {
			
			PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM emp");
			ResultSet rs = pstmt.executeQuery();
			while (rs.next()) {
				Emp emp = new Emp();
				emp.setEmpno(rs.getInt("empno"));
				emp.setEname(rs.getString("ename"));
				emp.setJob(rs.getString("job"));
				emp.setMgr(rs.getInt("mgr"));
				emp.setHiredate(rs.getTimestamp("hiredate"));
				emp.setSal(rs.getInt("sal"));
				emp.setComm(rs.getInt("comm"));
				emp.setDeptno(rs.getInt("deptno"));
				emps.add(emp);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return emps;
	} // end of 직원목록보기

	public Emp 직원한건보기(int empno) {
		Emp emp = new Emp();
		try {
			
			PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM emp WHERE empno = " + empno);
			ResultSet rs = pstmt.executeQuery();

			if (rs.next()) {
				emp.setEmpno(rs.getInt("empno"));
				emp.setEname(rs.getString("ename"));
				emp.setJob(rs.getString("job"));
				emp.setMgr(rs.getInt("mgr"));
				emp.setHiredate(rs.getTimestamp("hiredate"));
				emp.setSal(rs.getInt("sal"));
				emp.setComm(rs.getInt("comm"));
				emp.setDeptno(rs.getInt("deptno"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return emp;
	}
}
package service;

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

public class MyService {

	private EmpDao empDao; // 컴퍼지션
	private DeptDao deptDao; // 의존성 관계 MuService가 empDao, deptDao에 의존한다.
	private Connection conn;

	public MyService(EmpDao empDao, DeptDao deptDao, Connection conn) {
		this.empDao = empDao;
		this.deptDao = deptDao;
		this.conn = conn;
	}

	// 1. 직원 목록
	public ArrayList<Emp> 직원목록() {
		return empDao.직원목록보기();
	}

	// 2. 직원 상세보기
	public Emp 직원목록(int empno) {
		return empDao.직원한건보기(empno);
	}

	// 3. 직원 추가
	public int 직원추가(Emp emp) {
		return empDao.직원추가(emp);
	}

	// 4. 부서 추가
	public int 부서추가(Dept dept) {
		return deptDao.부서추가(dept);
	}

	// 5. TF팀 창설 Dept(*), ArrayList<Integer>
	public void TF팀창설(Dept dept, ArrayList<Integer> empnos) {
		int count = 0;
		count = count + deptDao.부서추가(dept);
		for (int i = 0; i < empnos.size(); i++) {
			count = count + empDao.직원수정(empnos.get(i), dept.getDeptno());
		}

		try {
			if (count == empnos.size() + 1) {
				conn.commit();
				System.out.println("커밋됨");
			} else {
				conn.rollback();
				System.out.println("롤백됨");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
package service;

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

public class MyApp {

	public static void main(String[] args) {
		Connection conn = DBConnection.connection();
		EmpDao empDao = new EmpDao(conn);
		DeptDao deptDao = new DeptDao(conn);
		
		// 생성자 주입 (DI)
		MyService myService = new MyService(empDao, deptDao, conn);
		
		// given
		Dept dept = new Dept(70, "TF팀", "부산");
		ArrayList<Integer> empnos = new ArrayList<>();
		empnos.add(7369);
		empnos.add(7499);
		
		myService.TF팀창설(dept, empnos);
	}

}
package service;

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

public class DBConnection {
	// public이 붙어야 다른 패키지에서 import 가능
	public static Connection connection() { // 똑똑
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");

			Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "SCOTT", "TIGER");

			conn.setAutoCommit(false);
			return conn;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

conn.setAutoCommit(false); 해준다

 

 

'Java' 카테고리의 다른 글

스트림, 버퍼, BufferedWriter, BufferedReader  (0) 2022.08.22
try - catch  (0) 2022.08.19
UPDATE  (0) 2022.08.16
JavaDB통신 Entity, ArrayList  (0) 2022.08.16
Java DB 통신  (0) 2022.08.12
Comments