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


이전 예제에서 dbconnect.properties 그대로 가져온다.
내부 설정은 다음과 같이 해준다.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

<properties resource="dbinfo/dbconnect.properties" />

  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="DBCP">
        <property name="JDBC.driver" value="${driver}"/>
        <property name="JDBC.url" value="${url}"/>
        <property name="JDBC.username" value="${username}"/>
        <property name="JDBC.password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>


네임스페이스(Namespaces)에 대한 설명

네임스페이스(Namespaces)가 이전버전에서는 사실 선택사항이었다. 하지만 이제는 패키지경로를 포함한 전체 이름을 가진 구문을 구분하기 위해 필수로 사용해야 한다.

네임스페이스은 인터페이스 바인딩을 가능하게 한다. 네임스페이스을 사용하고 자바 패키지의 네임스페이스을 두면 코드가 깔끔해지고 마이바티스의 사용성이 크게 향상될 것이다.

이름 분석(Name Resolution): 타이핑을 줄이기 위해 마이바티스는 구문과 결과매핑, 캐시등의 모든 설정엘리먼트를 위한 이름 분석 규칙을 사용한다.

  • “com.mypackage.MyMapper.selectAllThings”과 같은 패키지를 포함한 전체 경로명(Fully qualified names)은 같은 형태의 경로가 있다면 그 경로내에서 직접 찾는다.
  • “selectAllThings”과 같은 짧은 형태의 이름은 모호하지 않은 엔트리를 참고하기 위해 사용될 수 있다. 그래서 짧은 이름은 모호해서 에러를 자주 보게 되니 되도록 이면 전체 경로를 사용해야 할 것이다.




5. 실행 클래스


package spring.mybatis.controller;


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


1) resultMap: <resultMap>으로 지정된 id에 의해서 테이블의 column 값이 property의 변수로 연결되어 결과를 리턴한다.

2) resultType: <resultType>은 별칭으로 지정된 자바 빈 클래스로 결과를 리턴한다. (테이블 컬럼과 자바빈 멤버 연결) mybatis-config.xml 파일에서 지정된 <typeAlias alias="Account"> 형식으로 별칭 사용 지정한다.

※ 위의 둘은 둘 다 써줄 수도 있으며 둘 다 생략도 가능하다.

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="spring.mybatis.dto.Account">
<!-- table 속성(컬럼)과 property과의 맵핑 -->
<resultMap type="spring.mybatis.dto.Account" id="AccountMap">
<result column="id" property="id"/>
<result column="pwd" property="pwd"/>
<result column="name" property="name"/>
</resultMap>


<select id="selectAll" resultMap="AccountMap" resultType="Account">
select * from account
</select>
<select id="selectAcc" parameterType="String" resultMap="AccountMap">
select * from account where id = #{id}
</select>
<insert id="insertAcc" parameterType="Account">
   insert into account values (
    #{id}, #{pwd}, #{name}
   )
</insert>


<delete id="deleteAcc" parameterType="String">
   delete from account where id = #{id}    
</delete>

<update id="updateAcc" parameterType="Account">
update account set pwd=#{pwd}, name=#{name} where id = #{id}
</update>


</mapper>





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

프로그램을 종료합니다.







Posted by netyhobby
,