"Java dao"의 두 판 사이의 차이
DB CAFE
(→java dao dto 예제) |
(→java dao dto 예제) |
||
2번째 줄: | 2번째 줄: | ||
https://m.blog.naver.com/khm900402/220303769941 | https://m.blog.naver.com/khm900402/220303769941 | ||
− | + | == DAO(Data Access Object) == | |
+ | - 데이터베이스 관련 작업을 전담하는 클래스 | ||
− | + | - 데이터베이스에 연결하여, 입력 , 수정, 삭제, 조회 등의 작업을 하는 클래스 | |
− | + | - CRUD 작업 | |
+ | |||
+ | C: Create => insert | ||
+ | |||
+ | R: Read => select | ||
+ | |||
+ | U: Update | ||
+ | |||
+ | D: Delete | ||
+ | |||
+ | |||
+ | == DTO(Data Transfer Object), VO(Value Object), Bean == | ||
+ | |||
+ | - 데이터 전달 단위, 객체를 표현하는 단위 | ||
+ | |||
+ | - 보통 테이블의 컬럼들을 멤버변수로 처리한다. | ||
+ | |||
+ | - 캡슐화된 객체여야 함(멤버변수는 private 으로, public getter/setter 필수) | ||
+ | |||
+ | === DTO 기본 예제 === | ||
+ | <source lang=java> | ||
+ | package jdbc_day3; | ||
+ | |||
+ | import java.sql.Timestamp; | ||
+ | |||
+ | public class PersonDTO { | ||
+ | /* | ||
+ | DTO(Data Transfer Object),VO(Value Object), Bean | ||
+ | -데이터 전달 단위, 객체를 표현하는 단위 | ||
+ | -보통 테이블의 컬럼들을 멤버변수로 처리한다 | ||
+ | -캡슐화된 객체여야 함(멤버변수는 private으로, public getter/setter필수) | ||
+ | */ | ||
+ | //1. 멤버변수 | ||
+ | private int no; | ||
+ | private String name; | ||
+ | private String tel; | ||
+ | private int age; | ||
+ | private Timestamp regdate; | ||
+ | |||
+ | //2. 생성자 | ||
+ | public PersonDTO() { | ||
+ | super(); | ||
+ | } | ||
+ | |||
+ | public PersonDTO(int no, String name, String tel, int age, Timestamp regdate) { | ||
+ | super(); | ||
+ | this.no = no; | ||
+ | this.name = name; | ||
+ | this.tel = tel; | ||
+ | this.age = age; | ||
+ | this.regdate = regdate; | ||
+ | } | ||
+ | |||
+ | //3. getter/setter | ||
+ | public int getNo() { | ||
+ | return no; | ||
+ | } | ||
+ | |||
+ | public void setNo(int no) { | ||
+ | this.no = no; | ||
+ | } | ||
+ | |||
+ | public String getName() { | ||
+ | return name; | ||
+ | } | ||
+ | |||
+ | public void setName(String name) { | ||
+ | this.name = name; | ||
+ | } | ||
+ | |||
+ | public String getTel() { | ||
+ | return tel; | ||
+ | } | ||
+ | |||
+ | public void setTel(String tel) { | ||
+ | this.tel = tel; | ||
+ | } | ||
+ | |||
+ | public int getAge() { | ||
+ | return age; | ||
+ | } | ||
+ | |||
+ | public void setAge(int age) { | ||
+ | this.age = age; | ||
+ | } | ||
+ | |||
+ | public Timestamp getRegdate() { | ||
+ | return regdate; | ||
+ | } | ||
+ | |||
+ | public void setRegdate(Timestamp regdate) { | ||
+ | this.regdate = regdate; | ||
+ | } | ||
+ | //4. toString | ||
+ | @Override | ||
+ | public String toString() { | ||
+ | return "PersonDTO [no=" + no + ", name=" + name + ", tel=" + tel | ||
+ | + ", age=" + age + ", regdate=" + regdate + "]"; | ||
+ | } | ||
+ | } | ||
+ | </source> | ||
+ | | ||
+ | |||
+ | |||
+ | |||
+ | | ||
+ | === DB연결과 자원 해제등의 작업을 하는 클래스 === | ||
+ | |||
+ | <source lang=java> | ||
+ | package jdbc_day3; | ||
+ | |||
+ | import java.sql.CallableStatement; | ||
+ | import java.sql.Connection; | ||
+ | import java.sql.DriverManager; | ||
+ | import java.sql.PreparedStatement; | ||
+ | import java.sql.ResultSet; | ||
+ | import java.sql.SQLException; | ||
+ | import java.sql.Statement; | ||
+ | |||
+ | public class DBManager { | ||
+ | // DB연결과 자원 해제등의 작업을 하는 클래스 | ||
+ | |||
+ | // static 초기화 블럭 - static 변수의 복잡한 초기화에 사용됨 | ||
+ | // 해당클래스가 메모리에 로드될 때 최초로 한번만 실행됨 | ||
+ | static{ | ||
+ | //1. 드라이버 로딩 | ||
+ | try { | ||
+ | Class.forName("oracle.jdbc.driver.OracleDriver"); | ||
+ | System.out.println("드라이버 로딩 성공!"); | ||
+ | } catch (ClassNotFoundException e) { | ||
+ | System.out.println("드라이버 로딩 실패"); | ||
+ | e.printStackTrace(); | ||
+ | } | ||
+ | } | ||
+ | public static Connection getConnection() throws SQLException{ | ||
+ | //2. db연결하기 위한 Connection 객체 생성 | ||
+ | String url="jdbc:oracle:thin:@JKH03:1521:XE"; | ||
+ | String user="javauser1", pwd="java"; | ||
+ | Connection conn = DriverManager.getConnection(url, user, pwd); | ||
+ | System.out.println("DB연결, conn="+conn); | ||
+ | return conn; | ||
+ | } | ||
+ | |||
+ | public static void dbClose(ResultSet rs, PreparedStatement ps, Connection conn) throws SQLException{ | ||
+ | if(rs!=null)rs.close(); | ||
+ | if(ps!=null)ps.close(); | ||
+ | if(conn!=null)conn.close(); | ||
+ | System.out.println("자원반납, DB Close!!"); | ||
+ | } | ||
+ | |||
+ | public static void dbClose(PreparedStatement ps, Connection conn) throws SQLException{ | ||
+ | if(ps!=null)ps.close(); | ||
+ | if(conn!=null)conn.close(); | ||
+ | System.out.println("자원반납, DB Close!!"); | ||
+ | } | ||
+ | |||
+ | public static void dbClose(ResultSet rs, Statement stmt, Connection conn) throws SQLException{ | ||
+ | if(rs!=null)rs.close(); | ||
+ | if(stmt!=null)stmt.close(); | ||
+ | if(conn!=null)conn.close(); | ||
+ | System.out.println("자원반납, DB Close!!"); | ||
+ | } | ||
+ | |||
+ | public static void dbClose(Statement stmt, Connection conn) throws SQLException{ | ||
+ | if(stmt!=null)stmt.close(); | ||
+ | if(conn!=null)conn.close(); | ||
+ | System.out.println("자원반납, DB Close!!"); | ||
+ | } | ||
+ | |||
+ | public static void dbClose(ResultSet rs, CallableStatement cs, Connection conn) throws SQLException{ | ||
+ | if(rs!=null)rs.close(); | ||
+ | if(cs!=null)cs.close(); | ||
+ | if(conn!=null)conn.close(); | ||
+ | System.out.println("자원반납, DB Close!!"); | ||
+ | } | ||
+ | |||
+ | public static void dbClose(CallableStatement cs, Connection conn) throws SQLException{ | ||
+ | if(cs!=null)cs.close(); | ||
+ | if(conn!=null)conn.close(); | ||
+ | System.out.println("자원반납, DB Close!!"); | ||
+ | } | ||
+ | |||
+ | } | ||
+ | </source> | ||
+ | | ||
+ | |||
+ | |||
+ | |||
+ | |||
+ | |||
+ | | ||
+ | |||
+ | | ||
+ | |||
+ | | ||
+ | |||
+ | ===구문별 DTO,DAO 사용 방식 === | ||
+ | |||
+ | - JDBC DAO/DTO 코드는 사용방식이 공식과 같아서 똑같은 방식과 코드를 반복적으로 사용한다. | ||
+ | |||
+ | |||
+ | ==== insert / update 사용시==== | ||
+ | |||
+ | (매개변수 DTO) | ||
+ | |||
+ | <source lang=java> | ||
+ | public static int insertPerson(PersonDTO personDto) throws SQLException {//DB에 Insert | ||
+ | Connection conn = null; | ||
+ | PreparedStatement ps = null; | ||
+ | int rowCount = 0; | ||
+ | |||
+ | try{ | ||
+ | //1,2 .드라이버 로딩,db연결 | ||
+ | conn = DBManager.getConnection(); | ||
+ | |||
+ | //3.sql문장을 처리하는 PreparedStatement 객체 생성 | ||
+ | String sql = "insert into person(no,name,tel,age) values(person_seq.nextval,?,?,?)"; | ||
+ | |||
+ | ps = conn.prepareStatement(sql); | ||
+ | ps.setString(1, personDto.getName()); | ||
+ | ps.setString(2, personDto.getTel()); | ||
+ | ps.setInt(3,personDto.getAge()); | ||
+ | |||
+ | //4.실행 | ||
+ | rowCount = ps.executeUpdate(); | ||
+ | System.out.println("person 테이블 입력 처리, rowCount = "+rowCount); | ||
+ | }finally{ | ||
+ | DBManager.dbClose(ps, conn); | ||
+ | } | ||
+ | return rowCount; | ||
+ | } | ||
+ | </source> | ||
+ | | ||
+ | |||
+ | |||
+ | |||
+ | ==== delete 사용시 ==== | ||
+ | |||
+ | (매개변수 1개) | ||
+ | |||
+ | |||
+ | <source lang=java> | ||
+ | public static int deletePerson(int no) throws SQLException{ | ||
+ | |||
+ | Connection conn = null; | ||
+ | PreparedStatement ps = null; | ||
+ | PersonDTO dto = new PersonDTO(); | ||
+ | int rowCount=0; | ||
+ | |||
+ | try{ | ||
+ | //2.sb연결 | ||
+ | conn = DBManager.getConnection(); | ||
+ | |||
+ | //3.sql문장 처리 | ||
+ | String sql = "delete from person where no=?"; | ||
+ | ps = conn.prepareStatement(sql); | ||
+ | ps.setInt(1,no); | ||
+ | |||
+ | //4.실행 | ||
+ | rowCount = ps.executeUpdate(); | ||
+ | |||
+ | }finally{ | ||
+ | DBManager.dbClose(ps, conn); | ||
+ | } | ||
+ | return rowCount; | ||
+ | }//deletePerson | ||
+ | </source> | ||
+ | |||
+ | ==== Select 사용시 - Select 는 사용 방법이 2종류 ==== | ||
+ | |||
+ | ===== 여러개의 레코드일 경우 ===== | ||
+ | (ArrayList 사용) | ||
+ | ★ tip - ArrayList 사용시 for문은 기본적으로 사용! | ||
+ | |||
+ | |||
+ | <source lang=java> | ||
+ | public static List<PersonDTO> selectAll() throws SQLException {//전체 조회 작업 | ||
+ | |||
+ | //db - person 테이블 전체 조회 | ||
+ | Connection conn = null; | ||
+ | PreparedStatement ps = null; | ||
+ | ResultSet rs = null; | ||
+ | //여러 개의 레코드를 저장하기 위한 컬랙션 | ||
+ | // => 여러 개의 dto를 담기 위한 컬렉션 | ||
+ | List<PersonDTO> list = new ArrayList<PersonDTO>(); | ||
+ | |||
+ | try{ | ||
+ | //1,2. 드라이버 로딩 , db연결 | ||
+ | conn = DBManager.getConnection(); | ||
+ | |||
+ | //3.preparedStatement | ||
+ | String sql = "select * from person order by no desc"; | ||
+ | ps = conn.prepareStatement(sql); | ||
+ | rs = ps.executeQuery(); | ||
+ | |||
+ | while(rs.next()){ | ||
+ | |||
+ | int no = rs.getInt("no"); | ||
+ | String name = rs.getString("name"); | ||
+ | String tel = rs.getString("tel"); | ||
+ | int age = rs.getInt("age"); | ||
+ | Timestamp regdate = rs.getTimestamp("regdate"); | ||
+ | PersonDTO personDto = new PersonDTO(no, name, tel, age, regdate); | ||
+ | |||
+ | //한 개의 레코드를 dto에 저장한다 | ||
+ | //한 개의 레코드는 하나의 dto | ||
+ | //각 레코드(dto)를 컬렉션에 저장 | ||
+ | list.add(personDto); | ||
+ | }//while | ||
+ | System.out.println("전체 조회 결과 list.size() :"+list.size()); | ||
+ | }finally{ | ||
+ | DBManager.dbClose(rs, ps, conn); | ||
+ | } | ||
+ | return list; | ||
+ | } | ||
+ | </source> | ||
+ | |||
+ | ====== 한개의 레코드일 경우 ===== | ||
+ | (매개변수 1개) | ||
+ | |||
+ | |||
+ | <source lang=java> | ||
+ | public static PersonDTO selectByNo(int no) throws SQLException{ | ||
+ | |||
+ | Connection conn = null; | ||
+ | PreparedStatement ps = null; | ||
+ | ResultSet rs = null; | ||
+ | //한 개의 레코드를 하나의 dto로 묶어서 리턴한다. | ||
+ | PersonDTO dto = new PersonDTO(); | ||
+ | |||
+ | try{ | ||
+ | //2.db연결 | ||
+ | conn = DBManager.getConnection(); | ||
+ | |||
+ | //3.sql문장 처리 | ||
+ | String sql = "select * from person where no=?"; | ||
+ | ps = conn.prepareStatement(sql); | ||
+ | ps.setInt(1,no); | ||
+ | |||
+ | //4.실행 | ||
+ | rs = ps.executeQuery(); | ||
+ | if(rs.next()){ | ||
+ | |||
+ | int age = rs.getInt("age"); | ||
+ | String name = rs.getString("name"); | ||
+ | String tel = rs.getString("tel"); | ||
+ | Timestamp regdate = rs.getTimestamp("regdate"); | ||
+ | |||
+ | //하나의 레코드를 하나의 dto로 묶어준다. | ||
+ | dto.setAge(age); | ||
+ | dto.setName(name); | ||
+ | dto.setNo(no); | ||
+ | dto.setRegdate(regdate); | ||
+ | dto.setTel(tel); | ||
+ | } | ||
+ | //System.out.println("번호로 조회, dto ="+dto);//toString의 값이 찍힌다. | ||
+ | }finally{ | ||
+ | DBManager.dbClose(rs, ps, conn); | ||
+ | } | ||
+ | return dto; | ||
+ | } | ||
+ | </source> |
2021년 6월 7일 (월) 23:29 기준 최신판
thumb_up 추천메뉴 바로가기
- DBA { Oracle DBA 명령어 > DBA 초급 과정 > DBA 고급 과정 }
- 튜닝 { 오라클 튜닝 목록 }
- 모델링 { 데이터 모델링 가이드 }
목차
1 java dao dto 예제[편집]
2 DAO(Data Access Object)[편집]
- 데이터베이스 관련 작업을 전담하는 클래스
- 데이터베이스에 연결하여, 입력 , 수정, 삭제, 조회 등의 작업을 하는 클래스
- CRUD 작업
C: Create => insert
R: Read => select
U: Update
D: Delete
3 DTO(Data Transfer Object), VO(Value Object), Bean[편집]
- 데이터 전달 단위, 객체를 표현하는 단위
- 보통 테이블의 컬럼들을 멤버변수로 처리한다.
- 캡슐화된 객체여야 함(멤버변수는 private 으로, public getter/setter 필수)
3.1 DTO 기본 예제[편집]
package jdbc_day3;
import java.sql.Timestamp;
public class PersonDTO {
/*
DTO(Data Transfer Object),VO(Value Object), Bean
-데이터 전달 단위, 객체를 표현하는 단위
-보통 테이블의 컬럼들을 멤버변수로 처리한다
-캡슐화된 객체여야 함(멤버변수는 private으로, public getter/setter필수)
*/
//1. 멤버변수
private int no;
private String name;
private String tel;
private int age;
private Timestamp regdate;
//2. 생성자
public PersonDTO() {
super();
}
public PersonDTO(int no, String name, String tel, int age, Timestamp regdate) {
super();
this.no = no;
this.name = name;
this.tel = tel;
this.age = age;
this.regdate = regdate;
}
//3. getter/setter
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Timestamp getRegdate() {
return regdate;
}
public void setRegdate(Timestamp regdate) {
this.regdate = regdate;
}
//4. toString
@Override
public String toString() {
return "PersonDTO [no=" + no + ", name=" + name + ", tel=" + tel
+ ", age=" + age + ", regdate=" + regdate + "]";
}
}
3.2 DB연결과 자원 해제등의 작업을 하는 클래스[편집]
package jdbc_day3;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBManager {
// DB연결과 자원 해제등의 작업을 하는 클래스
// static 초기화 블럭 - static 변수의 복잡한 초기화에 사용됨
// 해당클래스가 메모리에 로드될 때 최초로 한번만 실행됨
static{
//1. 드라이버 로딩
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("드라이버 로딩 성공!");
} catch (ClassNotFoundException e) {
System.out.println("드라이버 로딩 실패");
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException{
//2. db연결하기 위한 Connection 객체 생성
String url="jdbc:oracle:thin:@JKH03:1521:XE";
String user="javauser1", pwd="java";
Connection conn = DriverManager.getConnection(url, user, pwd);
System.out.println("DB연결, conn="+conn);
return conn;
}
public static void dbClose(ResultSet rs, PreparedStatement ps, Connection conn) throws SQLException{
if(rs!=null)rs.close();
if(ps!=null)ps.close();
if(conn!=null)conn.close();
System.out.println("자원반납, DB Close!!");
}
public static void dbClose(PreparedStatement ps, Connection conn) throws SQLException{
if(ps!=null)ps.close();
if(conn!=null)conn.close();
System.out.println("자원반납, DB Close!!");
}
public static void dbClose(ResultSet rs, Statement stmt, Connection conn) throws SQLException{
if(rs!=null)rs.close();
if(stmt!=null)stmt.close();
if(conn!=null)conn.close();
System.out.println("자원반납, DB Close!!");
}
public static void dbClose(Statement stmt, Connection conn) throws SQLException{
if(stmt!=null)stmt.close();
if(conn!=null)conn.close();
System.out.println("자원반납, DB Close!!");
}
public static void dbClose(ResultSet rs, CallableStatement cs, Connection conn) throws SQLException{
if(rs!=null)rs.close();
if(cs!=null)cs.close();
if(conn!=null)conn.close();
System.out.println("자원반납, DB Close!!");
}
public static void dbClose(CallableStatement cs, Connection conn) throws SQLException{
if(cs!=null)cs.close();
if(conn!=null)conn.close();
System.out.println("자원반납, DB Close!!");
}
}
3.3 구문별 DTO,DAO 사용 방식[편집]
- JDBC DAO/DTO 코드는 사용방식이 공식과 같아서 똑같은 방식과 코드를 반복적으로 사용한다.
3.3.1 insert / update 사용시[편집]
(매개변수 DTO)
public static int insertPerson(PersonDTO personDto) throws SQLException {//DB에 Insert
Connection conn = null;
PreparedStatement ps = null;
int rowCount = 0;
try{
//1,2 .드라이버 로딩,db연결
conn = DBManager.getConnection();
//3.sql문장을 처리하는 PreparedStatement 객체 생성
String sql = "insert into person(no,name,tel,age) values(person_seq.nextval,?,?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1, personDto.getName());
ps.setString(2, personDto.getTel());
ps.setInt(3,personDto.getAge());
//4.실행
rowCount = ps.executeUpdate();
System.out.println("person 테이블 입력 처리, rowCount = "+rowCount);
}finally{
DBManager.dbClose(ps, conn);
}
return rowCount;
}
3.3.2 delete 사용시[편집]
(매개변수 1개)
public static int deletePerson(int no) throws SQLException{
Connection conn = null;
PreparedStatement ps = null;
PersonDTO dto = new PersonDTO();
int rowCount=0;
try{
//2.sb연결
conn = DBManager.getConnection();
//3.sql문장 처리
String sql = "delete from person where no=?";
ps = conn.prepareStatement(sql);
ps.setInt(1,no);
//4.실행
rowCount = ps.executeUpdate();
}finally{
DBManager.dbClose(ps, conn);
}
return rowCount;
}//deletePerson
3.3.3 Select 사용시 - Select 는 사용 방법이 2종류[편집]
3.3.3.1 여러개의 레코드일 경우[편집]
(ArrayList 사용) ★ tip - ArrayList 사용시 for문은 기본적으로 사용!
public static List<PersonDTO> selectAll() throws SQLException {//전체 조회 작업
//db - person 테이블 전체 조회
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
//여러 개의 레코드를 저장하기 위한 컬랙션
// => 여러 개의 dto를 담기 위한 컬렉션
List<PersonDTO> list = new ArrayList<PersonDTO>();
try{
//1,2. 드라이버 로딩 , db연결
conn = DBManager.getConnection();
//3.preparedStatement
String sql = "select * from person order by no desc";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
int no = rs.getInt("no");
String name = rs.getString("name");
String tel = rs.getString("tel");
int age = rs.getInt("age");
Timestamp regdate = rs.getTimestamp("regdate");
PersonDTO personDto = new PersonDTO(no, name, tel, age, regdate);
//한 개의 레코드를 dto에 저장한다
//한 개의 레코드는 하나의 dto
//각 레코드(dto)를 컬렉션에 저장
list.add(personDto);
}//while
System.out.println("전체 조회 결과 list.size() :"+list.size());
}finally{
DBManager.dbClose(rs, ps, conn);
}
return list;
}
3.3.3.2 = 한개의 레코드일 경우[편집]
(매개변수 1개)
public static PersonDTO selectByNo(int no) throws SQLException{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
//한 개의 레코드를 하나의 dto로 묶어서 리턴한다.
PersonDTO dto = new PersonDTO();
try{
//2.db연결
conn = DBManager.getConnection();
//3.sql문장 처리
String sql = "select * from person where no=?";
ps = conn.prepareStatement(sql);
ps.setInt(1,no);
//4.실행
rs = ps.executeQuery();
if(rs.next()){
int age = rs.getInt("age");
String name = rs.getString("name");
String tel = rs.getString("tel");
Timestamp regdate = rs.getTimestamp("regdate");
//하나의 레코드를 하나의 dto로 묶어준다.
dto.setAge(age);
dto.setName(name);
dto.setNo(no);
dto.setRegdate(regdate);
dto.setTel(tel);
}
//System.out.println("번호로 조회, dto ="+dto);//toString의 값이 찍힌다.
}finally{
DBManager.dbClose(rs, ps, conn);
}
return dto;
}