오라클
데이터 정의어
데이터 정의어( DDL )는 데이터베이스 데이터를 보관하고 관리하기 위해 제공되는 여러 객체(object)의 생성, 변경, 삭제
관련 기능을 수행한다.
데이터 정의어는 데이터 조작어 ( DML)와 달리 명령어를 수행하자마자 데이터베이스에 수행한 내용이 바로 반영이 되는 특성이 있다. 자동 COMMIT이 되므로 사용 시 주의
테이블을 생성하는 CREATE
CREATE TABLE EMP (
num NUMBER(4),
sal NUMBER(8,2),
name VARCHAR2(10),
hiredate DATE );
NUMBER(8,2)느 소수점 이하 두자리 숫자를 포함한 8자리 숫자를 저장할 수 있음을 뜻한다.
자연수는 6자리까지 표현 가능 123456.78과 같이 저장
DATE는 길이 지정이 필요 없는 자료형이기 때문에 소괄호를 사용하지 않음
다른 테이블을 복사하여 테이블 생성하기
create table emp2
as select * from emp
다른 테이블의 일부를 복사하여 테이블 생성하기
create table dep2
as select * from dept
where loc = 'NEW YORK'
기존 테이블의 열 구조만 복사하여 새 테이블 생성하기 ( 빈테이블 )
WHERE절 조건식의 결과 값이 언제나 false가 나오는 방법으로 사용
create table empdept_ddl
as select empno, ename, job, mgr, hiredate,
sal, comm, d.deptno, dname, loc
from emp, dept d
where 1 <> 1
테이블을 변경하는 ALTER
EMP 테이블 복사해서 EMP_ALTER 테이블 생성하기
create table emp_ALTER
as select * from emp
where deptno = 30;
ALTER 명령어로 HP 열 추가하기
alter table emp_alter
add hp VARCHAR2(20);
열 이름을 변경하는 RENAME
alter table emp_alter
rename COLUMN hp to tel;
ALTER 명령어로 EMPNO 열 길이 변경하기
alter table emp_alter
MODIFY empno number(5);
특정 열을 삭제할 때 사용하는 DROP
ALTER 명령어로 TEL열 삭제 하기
alter table emp_alter
drop column tel;
스프링 5
예제 프로젝트 만들기 ( 회원가입 처리, 비밀번호 변경 처리 )
pom.xml 파일 <dependencies> 추가
밑에 코드 추가
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
</dependency>
추가 된 파일
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sp5</groupId>
<artifactId>sp5-chap03</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
학생 데이터 관련 클래스
Student ( DTO ) , ( 비밀번호 변경 메서드 정의 )
package student;
import java.time.LocalDateTime;
//spring 패키지에서 WrongIdPasswordException 클래스를 import
import spring.WrongIdPasswordException;
public class Student {
private long sid; // 학생 ID를 저장하는 변수
private String phone; // 학생 전화번호를 저장하는 변수
private String passwd; // 학생 비밀번호를 저장하는 변수
private String name; // 학생 이름을 저장하는 변수
private LocalDateTime registerDateTime; // 학생 등록 일시를 저장하는 변수
public void setSid(long sid) { // sid 변수를 설정하는 메서드
this.sid = sid;
}
public long getSid() { // sid 변수를 반환하는 메서드
return sid;
}
public Student(String phone, String passwd, String name, LocalDateTime registerDateTime) { // 생성자 메서드
super();
this.phone = phone; // 전화번호를 인자로 받아 phone 변수에 저장
this.passwd = passwd; // 비밀번호를 인자로 받아 passwd 변수에 저장
this.name = name; // 이름을 인자로 받아 name 변수에 저장
this.registerDateTime = registerDateTime; // 등록 일시를 인자로 받아 registerDateTime 변수에 저장
}
public String getPhone() {
return phone;
}
public String getPasswd() {
return passwd;
}
public String getName() {
return name;
}
public LocalDateTime getRegisterDateTime() { // registerDateTime 변수를 반환하는 메서드
return registerDateTime;
}
// 비밀번호 변경 메서드
public void changePassword(String oldpasswd, String newpasswd) {
if (!passwd.equals(oldpasswd)) // 기존 비밀번호(oldpasswd)와 현재 비밀번호(passwd)가 다른 경우
throw new WrongIdPasswordException(); // WrongIdPasswordException 예외를 발생시킴
this.passwd = newpasswd; // 비밀번호를 새로운 비밀번호(newpasswd)로 변경
}
}
비밀번호 변경 시 기존 비밀번호와 현재 비밀번호가 다른 경우 예외 처리 상속
package student;
public class WrongIdPasswordException extends RuntimeException {
//비밀번호 변경 시 입력한 기존 비밀번호와 현재 비밀번호가 다른 경우 이 예외가 발생하도록 처리
}
DAO 정의
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class StudentDao {
private static long nextId = 0; // 다음 학생 ID를 생성하기 위한 정적 변수
private Map<String, Student> map = new HashMap<>();
// 학생 정보를 저장하기 위한 HashMap 컬렉션 생성 (키: 학생 전화번호, 값: 학생 객체)
public Student selectByPhone(String phone) {
// 전화번호(phone)를 기반으로 학생 정보를 조회하는 메서드
return map.get(phone); // HashMap에서 해당 전화번호를 키로 가지는 학생 객체를 반환
}
public void insert(Student student) {
// 학생 정보를 추가하는 메서드
student.setSid(++nextId); // 학생 객체에 다음 학생 ID를 설정
map.put(student.getPhone(), student); // HashMap에 학생 객체를 추가 (키: 전화번호, 값: 학생 객체)
}
public void update(Student student) {
// 학생 정보를 업데이트하는 메서드
map.put(student.getPhone(), student);
// HashMap에 새로운 학생 객체를 저장 (동일한 전화번호를 가진 학생 객체가 이미 존재하면 덮어씀)
}
public Collection<Student> selectAll() {
// 저장된 모든 학생 정보를 반환하는 메서드
return map.values(); // HashMap에 저장된 모든 학생 객체들의 컬렉션을 반환
}
}
학생가입 처리 관련 클래스
DTO, 학생 정보를 요청(request)하기 위한 클래스, 회원가입 할 때 비밀번호 같은지 확인
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class StudentRequest {
private String phone; // 학생 전화번호를 저장하는 변수
private String password; // 학생 비밀번호를 저장하는 변수
private String confirmPassword; // 비밀번호 확인을 위해 입력한 비밀번호를 저장하는 변수
private String name; // 학생 이름을 저장하는 변수
public boolean isPasswordEqualToConfirmPassword() {
// 비밀번호와 확인용 비밀번호가 일치하는지 확인하는 메서드
return password.equals(confirmPassword); // 비밀번호와 확인용 비밀번호를 비교하여 결과 반환
}
}
동일한 학생 정보가 존재하는 경우 사용자한태 알리는 예외처리
package student;
public class DuplicationStudentException extends RuntimeException {
// DuplicationStudentException 클래스를 정의하며 RuntimeException 클래스를 상속받음
public DuplicationStudentException(String message) {
// 생성자 메서드
super(message);
// 부모 클래스인 RuntimeException의 생성자를 호출하고, 인자로 전달된 메시지를 설정함
}
//동일한 전화번호를 가진 학생이 이미 등록되어 있으면 이 예외를 발생시키고
//해당 메시지를 사용자에게 알리는 용도로 사용
}
학생 정보 등록 서비스를 제공하는 클래스, StudentDao 객체를 의존성 주입
package student;
import java.time.LocalDateTime;
import spring.DuplicateMemberException;
public class StudentRegisterService {
private StudentDao studentDao;
// 생성자를 통해 StudentDao 객체를 주입받음
// 의존 객체를 생성자를 통해 주입한다.
public StudentRegisterService(StudentDao studentDao) {
this.studentDao = studentDao;
}
// 학생 등록을 수행하는 메서드
public Long regist(StudentRequest req) {
// 입력한 전화번호로 이미 등록된 학생이 있는지 조회
Student student = studentDao.selectByPhone(req.getPhone());
// 같은 전화번호를 가진 학생이 이미 존재하면 예외 발생
if (student != null) {
throw new DuplicateMemberException("dup phone " + req.getPhone());
// DuplicateMemberException 예외를 발생시키고 메시지를 설정하여 사용자에게 중복된 전화번호임을 알림
}
// 같은 전화번호를 가진 학생이 존재하지 않으면 DB에 삽입
Student newStudent = new Student(
req.getPhone(), req.getPassword(), req.getName(),
LocalDateTime.now());
studentDao.insert(newStudent); // 학생 정보를 DB에 삽입
// 새로 등록한 학생의 ID를 반환
return newStudent.getSid();
}
}
암호변경 관련 클래스
암호 변경 서비스 클래스
package student;
import spring.MemberNotFoundException;
public class StudentChangePasswordService {
private StudentDao studentDao; // StudentDao 객체를 참조하는 멤버 변수
public void changePassword(String phone, String oldPwd, String newPwd) {
// 학생의 비밀번호 변경 메서드
Student student = studentDao.selectByPhone(phone);
// 전화번호를 기반으로 학생 정보를 조회
if (student == null)
// 조회된 학생이 없으면 (해당 전화번호로 등록된 학생이 없으면)
throw new MemberNotFoundException();
// MemberNotFoundException 예외를 발생시킴
student.changePassword(oldPwd, newPwd);
// 학생 객체의 비밀번호 변경 메서드 호출 (기존 비밀번호를 새로운 비밀번호로 변경)
studentDao.update(student);
// 변경된 학생 정보를 업데이트 (DB에 반영)
}
public void setStudentDao(StudentDao studentDao) {
// StudentDao 객체를 주입하는 setter 메서드
this.studentDao = studentDao;
// 주입받은 StudentDao 객체를 멤버 변수에 설정
}
}
특정 학생 정보를 조회할 때, 해당 학생이 존재하지 않는 경우에 발생하는 예외처리
package student;
public class StudentNotFoundException extends RuntimeException {
// StudentNotFoundException은 RuntimeException의 하위 클래스이므로,
// 이 클래스는 Unchecked Exception으로 분류됨.
// Unchecked Exception은 명시적으로 예외를 처리하지 않아도 컴파일 시점에서 체크되지 않으며,
// 예외가 발생하면 런타임에 예외가 전파되어 프로그램 실행이 중단됨.
// 특정 학생 정보를 조회할 때, 해당 학생이 존재하지 않는 경우에 발생하는 예외로 사용될 수 있음.
// 예를 들어, 특정 학생의 ID를 기반으로 정보를 조회하는 메서드에서 해당 학생이 존재하지 않는 경우에
// 이 예외를 발생시키고 메시지를 설정하여 사용자에게 해당 학생을 찾을 수 없음을 알릴 수 있음.
}
객체 조립기
객체를 생성하고 의존 객체를 주입하는 기능을 제공한다. 또 한 특정 객체가 필요한 곳에 객체를 제공한다.
학생 정보와 관련된 객체들을 조립(Assemble)하는 클래스
package student;
public class AssemStudent {
// AssemStudent 클래스 정의
private StudentDao studentDao; // StudentDao 객체를 가리키는 멤버 변수
private StudentRegisterService SregSvc; // StudentRegisterService 객체를 가리키는 멤버 변수
private StudentChangePasswordService pwdSvc; // StudentChangePasswordService 객체를 가리키는 멤버 변수
public AssemStudent() {
// 생성자 메서드
studentDao = new StudentDao();
// 새로운 StudentDao 객체를 생성하여 studentDao 멤버 변수에 설정
SregSvc = new StudentRegisterService(studentDao);
// StudentRegisterService 객체를 생성하고 studentDao를 인자로 넘겨서 SregSvc 멤버 변수에 설정
pwdSvc = new StudentChangePasswordService();
// StudentChangePasswordService 객체를 생성하여 pwdSvc 멤버 변수에 설정
pwdSvc.setStudentDao(studentDao);
// pwdSvc의 setStudentDao 메서드를 사용하여 studentDao를 설정 (의존 객체 주입)
}
public StudentDao getStudentDao() {
// studentDao 멤버 변수를 반환하는 메서드
return studentDao;
}
public StudentRegisterService getStudentRegisterService() {
// SregSvc 멤버 변수를 반환하는 메서드
return SregSvc;
}
public StudentChangePasswordService getStudentChangePasswordService() {
// pwdSvc 멤버 변수를 반환하는 메서드
return pwdSvc;
}
}
실행
package student;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import spring.DuplicateMemberException;
import spring.MemberNotFoundException;
import spring.WrongIdPasswordException;
public class MainForAssemStudent {
public static void main(String[] args) throws IOException {
// 메인 메서드
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
// 사용자 입력을 받는 반복문
while (true) {
System.out.println("명령어를 입력하세요:");
String command = reader.readLine(); // 사용자 입력 받기
if (command.equalsIgnoreCase("exit")) {
System.out.println("종료합니다.");
break;
}
if (command.startsWith("new ")) {
// "new"로 시작하는 명령어 처리
processNewCommand(command.split(" "));
continue;
} else if (command.startsWith("change ")) {
// "change"로 시작하는 명령어 처리
processChangeCommand(command.split(" "));
continue;
}
printHelp(); // 잘못된 명령어일 경우 도움말 출력
}
}
private static AssemStudent assemStudent = new AssemStudent();
private static void processNewCommand(String[] arg) {
// "new" 명령어 처리
if (arg.length != 5) {
printHelp();
return;
}
StudentRegisterService SregSvc = assemStudent.getStudentRegisterService();
// AssemStudent에서 StudentRegisterService 객체를 가져옴
StudentRequest Sreq = new StudentRequest();
Sreq.setPhone(arg[1]);
Sreq.setName(arg[2]);
Sreq.setPassword(arg[3]);
Sreq.setConfirmPassword(arg[4]);
if (!Sreq.isPasswordEqualToConfirmPassword()) {
System.out.println("암호와 확인이 일치하지 않습니다.\n");
return;
}
try {
SregSvc.regist(Sreq);
// 학생 정보 등록을 수행
System.out.println("등록했습니다.\n");
} catch (DuplicateMemberException e) {
System.out.println("이미 존재하는 폰번호입니다.\n");
}
}
private static void processChangeCommand(String[] arg) {
// "change" 명령어 처리
if (arg.length != 4) {
printHelp();
return;
}
StudentChangePasswordService studentChangePasswordService =
assemStudent.getStudentChangePasswordService();
// AssemStudent에서 StudentChangePasswordService 객체를 가져옴
try {
studentChangePasswordService.changePassword(arg[1], arg[2], arg[3]);
// 학생 비밀번호 변경을 수행
System.out.println("암호를 변경했습니다.\n");
} catch (MemberNotFoundException e) {
System.out.println("존재하지 않는 폰번호입니다.\n");
} catch (WrongIdPasswordException e) {
System.out.println("폰번호와 암호가 일치하지 않습니다.\n");
}
}
private static void printHelp() {
// 도움말 출력
System.out.println();
System.out.println("잘못된 명령입니다. 아래 명령어 사용법을 확인하세요.");
System.out.println("명령어 사용법:");
System.out.println("new 폰번호 이름 암호 암호확인");
System.out.println("change 폰번호 현재비번 변경비번");
System.out.println();
}
}
예외 처리를 상속으로 처리하면 클래스파일이 추가로 생기지만 장점은 어디서 에러가 나는지 확인하기 쉽고
사용자한태 어디서 에러가 낫는지 확인이 가능해서 좋은 거 같다.
'프로젝트 기반 자바(JAVA) 응용 SW개발자 취업과정' 카테고리의 다른 글
2023-07-24 47일차 (0) | 2023.07.24 |
---|---|
2023-07-21 46일차 (0) | 2023.07.21 |
2023-07-19 44일차 (0) | 2023.07.19 |
2023-07-18 43일차 (0) | 2023.07.18 |
2023-07-17 42일차 (0) | 2023.07.17 |