1. pom.xml 수정
MyBatis 모듈을 추가하여 자동으로 다운로드 받게 한다.
<!-- MyBatis 모듈 추가 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.2</version>
</dependency>
2. DB 구축
STS의 리소스 폴더에 Account.sql를 만들어 다음과 같이 입력한다.
drop table account purge;
create table account(
id varchar2(20) primary key,
pwd varchar2(20),
name varchar2(20)
);
insert into account values('hongkd', '123', '홍길동');
insert into account values('leess', '456', '이순신');
insert into account values('kangkc', '789', '강감찬');
select * from account;
3. 자바빈 클래스 생성
package spring.mybatis.dto;
public class Account {
private String id;
private String pwd;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
4. MyBatis 설정 파일: mybatis-config.xml
네임스페이스(Namespaces)에 대한 설명
네임스페이스(Namespaces)가 이전버전에서는 사실 선택사항이었다. 하지만 이제는 패키지경로를 포함한 전체 이름을 가진 구문을 구분하기 위해 필수로 사용해야 한다.
네임스페이스은 인터페이스 바인딩을 가능하게 한다. 네임스페이스을 사용하고 자바 패키지의 네임스페이스을 두면 코드가 깔끔해지고 마이바티스의 사용성이 크게 향상될 것이다.
이름 분석(Name Resolution): 타이핑을 줄이기 위해 마이바티스는 구문과 결과매핑, 캐시등의 모든 설정엘리먼트를 위한 이름 분석 규칙을 사용한다.
- “com.mypackage.MyMapper.selectAllThings”과 같은 패키지를 포함한 전체 경로명(Fully qualified names)은 같은 형태의 경로가 있다면 그 경로내에서 직접 찾는다.
- “selectAllThings”과 같은 짧은 형태의 이름은 모호하지 않은 엔트리를 참고하기 위해 사용될 수 있다. 그래서 짧은 이름은 모호해서 에러를 자주 보게 되니 되도록 이면 전체 경로를 사용해야 할 것이다.
5. 실행 클래스
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Scanner;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import spring.mybatis.dto.Account;
public class AccountDaoImpl {
static SqlSession session; // static 메서드 안에 사용하므로 static형으로 선언
static{
// myBatis 설정 파일 지정
String resource = "dbinfo/mybatis-config.xml";
try { // 1. myBatis 설정 파일 읽기
InputStream reader = Resources.getResourceAsStream(resource);
// 2. SqlSessionFactory 객체 생성
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
// 3. Session 객체 열기
session = factory.openSession();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
AccountDaoImpl acc = new AccountDaoImpl();
acc.start();
}
public void start(){
Scanner sc = new Scanner(System.in);
boolean flag = true;
String id = "";
String pw = "";
String name = "";
Account account = new Account();
while(flag){
System.out.println("=================");
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.println("=================");
System.out.print("번호를 입력하세요: ");
int num = Integer.parseInt(sc.nextLine());
switch(num) {
case 1:
System.out.println("프로그램을 종료합니다.");
System.exit(0);
break;
case 2:
List<Account> list;
list = session.selectList("selectAll");
for(Account ac : list) {
System.out.printf("id:%s , pwd:%s , name:%s\n", ac.getId(), ac.getPwd(), ac.getName());
}
break;
case 3:
System.out.println("검색할 id를 입력하세요: ");
id = sc.nextLine();
account = (Account)session.selectOne("selectAcc", id);
if(account == null) { System.out.println("해당 id가 없습니다.");
}
else {
System.out.printf("id:%s , pwd:%s , name:%s\n", account.getId(), account.getPwd(), account.getName());
}
break;
case 4:
System.out.print("추가할 id: "); account.setId(sc.nextLine());
System.out.print("추가할 pw: "); account.setPwd(sc.nextLine());
System.out.print("추가할 name: "); account.setName(sc.nextLine());
session.insert("insertAcc", account);
session.commit();
break;
case 5:
System.out.println("삭제할 id를 입력하세요: ");
id = sc.nextLine();
account = (Account)session.selectOne("selectAcc", id);
if(account == null) { System.out.println("해당 id가 없습니다.");
}
else {
session.delete("deleteAcc", id);
session.commit();
System.out.println(id+"가 삭제되었습니다.");
}
break;
case 6:
System.out.println("수정할 id를 입력하세요: ");
id = sc.nextLine();
account = (Account)session.selectOne("selectAcc", id);
if(account == null) { System.out.println("해당 id가 없습니다.");
}
else {
System.out.print("변경할 pw: "); account.setPwd(sc.nextLine());
System.out.print("변경할 name: "); account.setName(sc.nextLine());
session.update("updateAcc", account);
session.commit();
}
break;
default:
System.out.println("잘못된 번호를 입력했습니다.");
break;
}
}
}
}
6. 각 명령에 따른 sql을 저장하는 설정 파일 Account.xml
7. 실행 결과
12:28:31.765 [main] DEBUG org.apache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
12:28:31.777 [main] DEBUG o.a.i.d.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
12:28:31.777 [main] DEBUG o.a.i.d.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
12:28:31.778 [main] DEBUG o.a.i.d.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
12:28:31.778 [main] DEBUG o.a.i.d.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
=================
1. 프로그램 종료.
2. 모든 유저 출력
3. 하나의 유저 출력
4. 유저 추가
5. 유저 정보 삭제
6. 유저 정보 수정
=================
번호를 입력하세요: 6
수정할 id를 입력하세요:
hkd
12:28:41.133 [main] DEBUG o.a.i.t.jdbc.JdbcTransaction - Opening JDBC Connection
12:28:41.349 [main] DEBUG o.a.i.d.pooled.PooledDataSource - Created connection 674483268.
12:28:41.351 [main] DEBUG spring.mybatis.dto.Account.selectAcc - ooo Using Connection [oracle.jdbc.driver.T4CConnection@2833cc44]
12:28:41.352 [main] DEBUG spring.mybatis.dto.Account.selectAcc - ==> Preparing: select * from account where id = ?
12:28:41.427 [main] DEBUG spring.mybatis.dto.Account.selectAcc - ==> Parameters: hkd(String)
해당 id가 없습니다.
=================
1. 프로그램 종료.
2. 모든 유저 출력
3. 하나의 유저 출력
4. 유저 추가
5. 유저 정보 삭제
6. 유저 정보 수정
=================
번호를 입력하세요: 2
12:28:46.026 [main] DEBUG spring.mybatis.dto.Account.selectAll - ooo Using Connection [oracle.jdbc.driver.T4CConnection@2833cc44]
12:28:46.026 [main] DEBUG spring.mybatis.dto.Account.selectAll - ==> Preparing: select * from account
12:28:46.026 [main] DEBUG spring.mybatis.dto.Account.selectAll - ==> Parameters:
id:abc , pwd:123 , name:아무개
id:yjs , pwd:5555 , name:유재석
id:hongkd , pwd:123 , name:홍길동
id:leess , pwd:456 , name:이순신
id:kangkc , pwd:789 , name:강감찬
=================
1. 프로그램 종료.
2. 모든 유저 출력
3. 하나의 유저 출력
4. 유저 추가
5. 유저 정보 삭제
6. 유저 정보 수정
=================
번호를 입력하세요: 6
수정할 id를 입력하세요:
hongkd
12:28:59.498 [main] DEBUG spring.mybatis.dto.Account.selectAcc - ooo Using Connection [oracle.jdbc.driver.T4CConnection@2833cc44]
12:28:59.499 [main] DEBUG spring.mybatis.dto.Account.selectAcc - ==> Preparing: select * from account where id = ?
12:28:59.499 [main] DEBUG spring.mybatis.dto.Account.selectAcc - ==> Parameters: hongkd(String)
변경할 pw: hhh
변경할 name: 홍석천
12:29:09.303 [main] DEBUG spring.mybatis.dto.Account.updateAcc - ooo Using Connection [oracle.jdbc.driver.T4CConnection@2833cc44]
12:29:09.303 [main] DEBUG spring.mybatis.dto.Account.updateAcc - ==> Preparing: update account set pwd=?, name=? where id = ?
12:29:09.303 [main] DEBUG spring.mybatis.dto.Account.updateAcc - ==> Parameters: hhh(String), 홍석천(String), hongkd(String)
12:29:09.306 [main] DEBUG o.a.i.t.jdbc.JdbcTransaction - Committing JDBC Connection [oracle.jdbc.driver.T4CConnection@2833cc44]
=================
1. 프로그램 종료.
2. 모든 유저 출력
3. 하나의 유저 출력
4. 유저 추가
5. 유저 정보 삭제
6. 유저 정보 수정
=================
번호를 입력하세요: 2
12:29:11.426 [main] DEBUG spring.mybatis.dto.Account.selectAll - ooo Using Connection [oracle.jdbc.driver.T4CConnection@2833cc44]
12:29:11.427 [main] DEBUG spring.mybatis.dto.Account.selectAll - ==> Preparing: select * from account
12:29:11.427 [main] DEBUG spring.mybatis.dto.Account.selectAll - ==> Parameters:
id:abc , pwd:123 , name:아무개
id:yjs , pwd:5555 , name:유재석
id:hongkd , pwd:hhh , name:홍석천
id:leess , pwd:456 , name:이순신
id:kangkc , pwd:789 , name:강감찬
=================
1. 프로그램 종료.
2. 모든 유저 출력
3. 하나의 유저 출력
4. 유저 추가
5. 유저 정보 삭제
6. 유저 정보 수정
=================
번호를 입력하세요: 1
프로그램을 종료합니다.
' Spring Framework' 카테고리의 다른 글
스프링 상식 테스트 (0) | 2016.04.26 |
---|---|
스프링에서 파일업로드 하기 (1) | 2016.04.15 |
iBATIS 실습: DB연동 구조 (완성) (0) | 2016.04.12 |
iBATIS 실습: DB연동 구조 (미완) (0) | 2016.04.12 |
스프링 JDBC 연동을 통한 쇼핑몰: 커넥션 풀 (0) | 2016.04.11 |