5주차 - 자바, 데이터베이스 (5)

2022. 9. 3. 16:10DataBase/Oracle

패키지가 만들어질때 일반적으로

메인이 되며 데이터를 입력받는 메인 클래스

데이터를 검증하고 출력을 담당하는 Service

데이터를 데이터베이스에 연결하는 DAO

그리고 데이터 객체를 가지고 있는 DTO로 나누어서 만든다.

라고 배웠다. 현장에서 어떻게 될지는 기업마다 다를테니 참고만 해두자.

지난 번에는 메인, DAO, DTO로 나누어서 만들었으니 이번에는

메인, service 인터페이스 , DAO 인터페이스, service, DAO, DTO 를 나누어서 만들어 볼 것이다.

이번에도 동일하게 간단한 회원가입을 하는 프로그램을 만들어보자.

 

 

아래는 DTO 의 생성

public class MemberDTO {
	private String email;
	private String name;
	private String mobile;
	
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
}

DAO의 인터페이스 생성

import java.util.ArrayList;

public interface IMemberDAO {

	public int isExists(String email);
	public void insert(MemberDTO member);
	public MemberDTO selectEmail(String email);
	public int delete(String email);
	public ArrayList<MemberDTO> selectAll();
	public void update(String email, String name, String mobile);	
}

DAO의 생성

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

public class MemberDAOImpl implements IMemberDAO {
	private static Connection con = null;
	private static PreparedStatement ps = null;
	private static ResultSet rs = null;

	public MemberDAOImpl() {
		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String user = "oracle";
		String password = "oracle";

		try {
			Class.forName("oracle.jdbc.OracleDriver");
			con = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public int isExists(String email) {
		String sql = "SELECT count(email) FROM jdbc_concept2 WHERE email=?";

		int count = 0;
		try {
			ps = con.prepareStatement(sql);
			ps.setString(1, email);
			rs = ps.executeQuery();

			if (rs.next()) {
				count = rs.getInt(1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return count;
	}

	@Override
	public void insert(MemberDTO member) {

		if (isExists(member.getEmail()) == 0) {
			String sql = "INSERT INTO jdbc_concept2 VALUES(?, ?, ?)";
			PreparedStatement ps = null;
			try {
				ps = con.prepareStatement(sql);
				ps.setString(1, member.getEmail());
				ps.setString(2, member.getName());
				ps.setString(3, member.getMobile());

				ps.executeUpdate();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public MemberDTO selectEmail(String email) {
		String sql = "SELECT * FROM jdbc_concept2 WHERE email=?";
		MemberDTO member = new MemberDTO();
		try {
			ps = con.prepareStatement(sql);
			ps.setString(1, email);
			rs = ps.executeQuery();
			if (rs.next()) {
				member.setEmail(rs.getString("email"));
				member.setName(rs.getString("name"));
				member.setMobile(rs.getString("mobile"));
				return member;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public int delete(String email) {
		String sql = "DELETE FROM jdbc_concept2 WHERE email=?";
		int check = 0;
		try {
			ps = con.prepareStatement(sql);
			ps.setString(1, email);
			check = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return check;
	}

	@Override
	public ArrayList<MemberDTO> selectAll() {
		ArrayList<MemberDTO> members = new ArrayList<MemberDTO>();

		String sql = "SELECT * FROM jdbc_concept2";
		try {
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				MemberDTO member = new MemberDTO();
				String email = rs.getString("email");
				String name = rs.getString("name");
				String mobile = rs.getString("mobile");
				member.setEmail(email);
				member.setName(name);
				member.setMobile(mobile);
				members.add(member);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return members;
	}

	@Override
	public void update(String email, String name, String mobile) {
		String sql = "UPDATE jdbc_concept2 SET name=?, mobile=? WHERE email=?";

		try {
			ps = con.prepareStatement(sql);
			ps.setString(1, name);
			ps.setString(2, mobile);
			ps.setString(3, email);
			ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void disconnection() {
		try {
			if (rs != null)
				rs.close();
			if (ps != null)
				ps.close();
			if (con != null)
				con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

Service 인터페이스 생성

public interface MemberService {
	public void insert(MemberDTO member);
	public MemberDTO selectEmail(String email);
	public ArrayList<MemberDTO> selectAll();
	public void delete(String email);
	public void update(String email, String name, String mobile);
	public void disconnection();
}

Service 생성

public class MemberServiceImpl implements MemberService {
	private MemberDAOImpl memberDao = new MemberDAOImpl();
	Scanner in = new Scanner(System.in);

	/*
	 * 입력값 전달받아 검증하기 DAO로 CRUD를 하기 위한 데이터를 전달 결과를 받을게 있다면 받아서 결과 출력, 
	    결과를 받을게 없고 출력은 있다면 출력
	 */
	public static void MemberService() {
	}

	@Override
	public void insert(MemberDTO member) {
		int index = memberDao.isExists(member.getEmail());
		if (index == 0) {
			memberDao.insert(member);
			System.out.println(member.getEmail() + "의 정보를 등록했습니다.");
		} else
			System.out.println(member.getEmail() + "는/은 등록된 이메일입니다.");
	}

	@Override
	public MemberDTO selectEmail(String email) {
		int index = memberDao.isExists(email);
		if (index == 0) {
			System.out.println(email + "는/은 등록된 정보가 아닙니다.");
		} else {
			MemberDTO selectData = memberDao.selectEmail(email);
			System.out.println("이메일 : " + selectData.getEmail());
			System.out.println("이름 : " + selectData.getName());
			System.out.println("전화번호 : " + selectData.getMobile());
		}
		System.out.println();
		return null;
	}

	@Override
	public ArrayList<MemberDTO> selectAll() {
		ArrayList<MemberDTO> members = new ArrayList<MemberDTO>();
		members = memberDao.selectAll();
		if (members.isEmpty() == false) {
			for (MemberDTO m : members) {
				System.out.println("이메일 : " + m.getEmail());
				System.out.println("이름 : " + m.getName());
				System.out.println("전화번호 : " + m.getMobile());
				System.out.println();
			}
		} else {
			System.out.println("등록 후 이용하세요");
		}
		return null;
	}

	@Override
	public void delete(String email) {
		int index = memberDao.isExists(email);

		if (index == 0) {
			System.out.println(email + "는/은 등록된 정보가 아닙니다.");
			return;
		}

		int rowCount = memberDao.delete(email);
		if (rowCount == 1) {
			System.out.println(email + "님의 정보가 삭제되었습니다.");
		} else if (rowCount == 0) {
			System.out.println(email + "님의 정보가 삭제되지 않았습니다. 다시 시도하세요");
		}

	}

	@Override
	public void update(String email, String name, String mobile) {
		int index = memberDao.isExists(email);

		if (index == 0) {
			System.out.println(email + "는/은 등록된 정보가 아닙니다.");
			return;
		}

		memberDao.update(email, name, mobile);
		System.out.println(email + "님의 정보가 변경되었습니다.");

	}

	@Override
	public void disconnection() {
		memberDao.disconnection();
	}
}

아래는 메인 클래스

public class Quiz4 {
	private static Scanner in = new Scanner(System.in);

	private static MemberServiceImpl memberService = new MemberServiceImpl();
	public static void main(String[] args) {
		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String user = "oracle";
		String password = "oracle";

		try {
			Class.forName("oracle.jdbc.OracleDriver");
			DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		while (true) {
			System.out.println("1. 회원 등록");
			System.out.println("2. 회원 검색");
			System.out.println("3. 회원 삭제");
			System.out.println("4. 회원 모두 보기");
			System.out.println("5. 회원 수정");
			System.out.println("6. 프로그램 종료");
			System.out.print("선택 > ");
			int select;
			try {
				select = Integer.parseInt(in.next());
			} catch (Exception e) {
				continue;
			}
			switch (select) {
			case 1:
				insert();
				break;
			case 2:
				selectEmail();
				break;
			case 3:
				delete();
				break;
			case 4:
				selectAll();
				break;
			case 5:
				update();
				break;
			case 6:
				exit();
			default:
				System.out.println("메뉴 확인 후 다시 입력하세요.");
			}
		}

	}

	private static void insert() {
		MemberDTO member = new MemberDTO();
		System.out.println("=== 회원 등록 ===");
		System.out.print("이메일 : ");
		member.setEmail(in.next());
		System.out.print("이름 : ");
		member.setName(in.next());
		System.out.print("전화번호 : ");
		member.setMobile(in.next());
		memberService.insert(member);
	}
	
	private static void selectEmail() {
		System.out.println("=== 회원 검색 ===");
		System.out.print("이메일 : ");
		String email = in.next();
		memberService.selectEmail(email);
	}
	private static void delete() {
		System.out.println("=== 회원 삭제 ===");
		System.out.print("이메일 : ");
		String email = in.next();
		memberService.delete(email);
	}
	
	private static void selectAll() {
		System.out.println("=== 회원 모두 보기 ===");
		memberService.selectAll();
	}
	private static void update() {
		System.out.println("=== 회원 수정 ===");
		System.out.print("이메일 : ");
		String email = in.next();
		System.out.print("이름 : ");
		String name = in.next();
		System.out.print("전화번호 : ");
		String mobile = in.next();
		memberService.update(email, name, mobile);
	}
	private static void exit() {
		memberService.disconnection();
		System.out.println("프로그램을 종료합니다.");
		System.exit(0);
	}
}