상세 컨텐츠

본문 제목

Java + myBatis (기본 자바 프로젝트에 마이바티스 연동)

프로그램 언어/Java

by husks 2016. 1. 27. 16:56

본문

반응형


개발을 하다보니 Spring 말고 기본 자바 프로젝트에서 Mybatis를 적용할 일이 생겼습니다.


해당 부분 내용 정리하겠습니다.



일반적인 자바 프로젝트에서 Mybatis 를 적용해 보았습니다. (오라클)



프로젝트 구조는 위 사진을 참고하시기 바랍니다.


jar 파일은 아래 링크를 다운 받으세요.



mybatis-3.3.0.jar


ojdbc14.jar


테이블 생성


1
2
3
4
CREATE TABLE BOOK(
  ID NUMBER, 
    NAME VARCHAR2(20 BYTE)
);





Book.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package model;
 
public class Book  {
 
    private int id;
    private String name;
 
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
 
    public String toString(){
        return "id: "+id+" Name: "+name;
    }
 
}




BookDAO.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package dao;
 
import java.util.List;
 
import model.Book;
 
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
 
public class BookDAO {
 
    private SqlSessionFactory sqlSessionFactory = null;
 
    public BookDAO(SqlSessionFactory sqlSessionFactory){
        this.sqlSessionFactory = sqlSessionFactory;
    }
 
    public  List<Book> selectAll(){
        List<Book> list = null;
        SqlSession session = sqlSessionFactory.openSession();
 
        try {
            list = session.selectList("Book.selectAll");
        } finally {
            session.close();
        }
 
        return list;
    }
 
    public Book selectById(int id){
        Book book = null;
        SqlSession session = sqlSessionFactory.openSession();
        try {
            book = session.selectOne("Book.selectById", id);
        } finally {
            session.close();
        }
 
        return book;
    }
 
    public int insert(Book book){
        int id = -1;
        SqlSession session = sqlSessionFactory.openSession();
 
        try {
            id = session.insert("Book.insert", book);
        } finally {
            session.commit();
            session.close();
        }
 
        return id;
    }
 
    public void update(Book book){
 
        SqlSession session = sqlSessionFactory.openSession();
 
        try {
            session.update("Book.update", book);
        } finally {
            session.commit();
            session.close();
        }
    }
 
    /**
     * Delete an instance of book from the database.
     * @param id value of the instance to be deleted.
     */
    public void delete(int id){
 
        SqlSession session = sqlSessionFactory.openSession();
 
        try {
            session.delete("Book.delete", id);
        } finally {
            session.commit();
            session.close();
        }
    }
}




MyBatisConnectionFactory.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package mybaits;
 
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 
public class MyBatisConnectionFactory {
 
    private static SqlSessionFactory sqlSessionFactory;
 
    static {
        try {
            String resource = "config/config.xml";
            Reader reader = Resources.getResourceAsReader(resource);
 
            if (sqlSessionFactory == null) {
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            }
        }
        catch (FileNotFoundException fileNotFoundException) {
            fileNotFoundException.printStackTrace();
        }
        catch (IOException iOException) {
            iOException.printStackTrace();
        }
    }
    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}




Main.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.List;
 
import dao.BookDAO;
import model.Book;
import mybaits.MyBatisConnectionFactory;
 
public class Main {
 
    public static void main(String[] args) {
 
        BookDAO bookDAO = new BookDAO(MyBatisConnectionFactory.getSqlSessionFactory());
 
        Book book = new Book();
 
        //Creat
        //2건을 입력한다.
        System.out.println("==INSERT==");
 
        book.setId(1);
        book.setName("홍길동전");
        bookDAO.insert(book);
 
        book.setId(2);
        book.setName("레미제라블"); 
        bookDAO.insert(book);
 
        //Read
        //입력한 리스트를 보여준다.
        List<Book> bookList = bookDAO.selectAll();
        for(Book bookInfo: bookList){
            System.out.println("BOOK ID: "+bookInfo.getId());
            System.out.println("BOOK NAME: "+bookInfo.getName());
        }
 
        //Update
        System.out.println("");
        System.out.println("==UPDATE==");
 
        //ID 2번의 이름을 업데이트 한다.
        book.setId(2);
        book.setName("해저 2만리");
        bookDAO.update(book);
 
        //Read
        //변경한 ID 2번의 이름을 보여준다ㅏ.
        book = bookDAO.selectById(2);
        System.out.println("BOOK ID: "+book.getId());
        System.out.println("BOOK NAME: "+book.getName());
 
        //Delete
        System.out.println("");
        System.out.println("==DELETE==");
 
        //2번을 삭제한다.
        bookDAO.delete(2);
 
        //Read
        //전체 리스트를 보여준다.
        bookList.clear();
        bookList = bookDAO.selectAll();
        for(Book bookInfo: bookList){
            System.out.println("BOOK ID: "+bookInfo.getId());
            System.out.println("BOOK NAME: "+bookInfo.getName());
        }
 
    }
 
}




config.xml


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?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>
    <typeAliases>
        <typeAlias alias="Book" type="model.Book"/>        
    </typeAliases>
 
    <environments default="development">
        <environment id="development">
          <transactionManager type="JDBC"/>
            <!--  connecting to Local MySql -->
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
                <property name="url" value="jdbc:oracle:thin:@url:1521:sid"/>
                <property name="username" value="name"/>
                <property name="password" value="password"/>
            </dataSource>
       </environment>
    </environments>
    <mappers>
       <mapper resource="sqlmap/Book.xml"/>
    </mappers>
</configuration>




Book.xml


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?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="Book">
 
    <resultMap id="result" type="Book">
        <result property="id" column="id"/>
        <result property="name" column="name"/>   
    </resultMap>
 
    <select id="selectAll" resultMap="result">
        SELECT * FROM BOOK
    </select>
 
    <select id="selectById" parameterType="int" resultMap="result">
        SELECT * FROM BOOK WHERE id = #{id}
    </select>
 
    <insert id="insert" parameterType="Book">
        INSERT INTO BOOK (id, name) VALUES (#{id}, #{name})
    </insert>
 
    <update id="update" parameterType="Book">
        UPDATE BOOK
        SET name = #{name}
        WHERE id = #{id} 
    </update>
 
    <delete id="delete" parameterType="int">
        DELETE from BOOK WHERE id = #{id}
    </delete>
</mapper>



결과



참고: http://hmkcode.com/java-mybatis-mysql/


반응형

관련글 더보기

댓글 영역