티스토리 뷰

DB/MyBatis

Mybatis - 환경설정 및 SELECT 예제

xoo | 수진 2023. 8. 4. 22:43

Mybatis 프레임워크

 

 

🎯 오늘 하루는


SQL을 지나 JDBC부터 조금씩 개념이 흔들리기 시작하는 것 같다.

JDBC에 비해 Mybatis는 쉽고 간결하다고 하나

환경설정, 새로운 문법 등 갑자기 한꺼번에 많은 지식들이 들어오다보니 정신이 없는 것은 사실이다. 😂

그래도 환경설정부터 과정을 하나하나 다 캡쳐해서 기록해놓으므로 다시 복습하기에는 좋을 것 같다.

계속 계속 봐야지. 결국은 익숙해지는 방법 뿐 !

 

 

 

 

📌 개요


JDBC 사용을 효율적으로, 편리하게, 파워풀하게 사용하도록 만든 프레임워크이다.

즉, 자바 개발자들이 데이터베이스를 쉽게 다룰 수 있도록 도와주는 오픈 소스 ORM(Object-Relational Mapping) 프레임워크이다.

 

 

 

📌 mybatis.org


mybatis.org  >  products  >  3 docs

 

 

 

 

📌 JDBC와 Mybatis 간단 비교

  • JDBC API는 Driver Manager를 사용하여 각 DB에 맞는 드라이버를 로딩, 해제한다.
  • 개발자는 JDBC API를 사용하여 DB 연결한다.
  • DB 연결을 위한 Connection 할당, 종료 같은 부수적인 코드 증가된다.

➡ 이러한 복잡성을 줄이기 위해 persistence framework인 MyBatis, JPA 등을 사용한다.

 

 

 

 

📌 Mybatis의 주요 장점


  1. 유연성SQL 쿼리를 직접 작성할 수 있으므로 매우 유연하다. 또한, MyBatis는 동적 쿼리를 작성할 수 있다.
  2. 간결성: MyBatis는 SQL 쿼리와 프로그래밍 언어 코드를 분리하기 때문에 코드가 간결해져 유지보수에 용이하다.
  3. 성능: MyBatis는 캐시 기능을 제공하여 데이터베이스 연산 속도를 높일 수 있다.
  4. 다양한 데이터베이스 지원: MyBatis는 다양한 데이터베이스에 대한 지원을 제공합니다.

 

 

📌Mybatis의 주요 컴포넌트


이름 설명
MyBatis 설정파일 (mybatis-config.xml) mybatis의 메인 환경설정 파일 ( DB의 접속 정보 또는 Mapping 파일의 경로, alias 등을 설정하는 XML 파일 )
SqlSessionFactoryBuilder build() 메소드를 통해 mybatis-config를 로딩하여 SqlSessionFactory 객체를 생성 
SqlSessionFactory SqlSession 객체에 대한 팩토리 객체 ( SqlSession을 생성 )
이 객체의 opensession() 메소드를 통해 SqlSession 객체를 얻을 수 있음
SqlSession Mapper XML에 등록된 Sql을 실행하기 위한 API 제공
가장 핵심적인 역할을 하는 SQL의 실행이나 트랜잭션 관리를 수행
Thread-Safe 하지 않으므로 thread 마다 필요에 따라 생성
Mapping File (mapper.xml) SQL과 객체 매핑 설정을 하는 XML 파일

 

 

 

 

📌 사용방법


  1. RDBMS 설치 (오라클)
  2. 오라클 드라이버 (ojdbc6_g.jar)
  3. mybatis 기능을 가진 jar 파일 다운(products - MyBatis 3 - download)
    https://github.com/mybatis/mybatis-3/releases
    ( 압축 다 풀면 나오는 mybatis-3.5.13.jar )
  4. 오라클 드라이버와 mybatis jar 파일 2개를 build path 한다.

 

 

 

 

5. 2개의 xml 파일 작성 ⇒ src 폴더에 저장, 패키지 이용 가능

  • 설정정보 저장 xml
    • 1개 작성
    • Configuration.xml
  • sql 저장 xml
    • 테이블 당 하나씩 작성
    • 명명법: 테이블명Mapper.xml
    • Mapper는 DB 쿼리와 <-> 자바 메서드()를 매핑하는 역할
    • ex) DeptMapper.xml, EmpMapper.xml
① src에 New file 생성 - Configuration.xml

 

https://mybatis.org/mybatis-3/getting-started.html 에서 복붙하기

 

③ 원래 $ 있던 곳에 복붙한다.
     - $ 지우고 복붙할 것
     - 공백 없을 것
<property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
<property name="username" value="SCOTT"/>
<property name="password" value="TIGER"/>

 

④ src에 new file 생성 => DeptMapper.xml

 

 

⑤ https://mybatis.org/mybatis-3/getting-started.html
    DeptMapper.xml에 복붙하기

 

 

⑥ JDBC와의 차이점
1. JDBC와 다르게 4가지 정보 파일들이 외부파일로 나옴
2. 세미콜론 ; 생략
3. ? 대신 #{ } 쓴다.

 

⑦ 테이블 전체를 가져오는 경우와
     where을 써서 특정한 것만 지정 선택 하는 경우

 

 

⑧ #{ } 이 있을 경우
    반드시 parameterType에 데이터 타입을 지정해준다.

 

 

⑨ #{ } 이 여러 개 라고 해서 parameterType을 여러 개 지정하는 것은 불가능

 

 

⑩ 반드시 하나의 파라미터 타입만 작성한다.

 

 


 

 

⑫ 하나의 행이 저장될 곳 ⇒ DTO

 

 

resultType="DeptDTO" => SELECT 해서 나온 레코드 한 개를 DTO에 자동으로 저장하겠다.
    JDBC의 DeptDTO dto = new DeptDAO(); 와 같은 기능

 

 

⑭ DTO.java 에서 컬럼 헤더와 동일한 변수 작성
     getter / setter
     기본생성자 ★

 

 

parameterType=”DeptDTO”

 

 

16. namespace의 이름이 중복되지 않게 한다.

 

 

17. Configuration.xml 에서 resource 값을 namespace 이름으로 변경해주기

 

 

 

6.  자바 파일에서 Configuration.xml 을 읽음
    String resource = "Configuration.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

18. new class => DeptMain.java 

 

 

19. 복붙하고 import 해주는 과정


  Ctrl + Shift + o 해서 import 해주기


완료된 import 목록

 

 

 

7. SqlSession 얻고 메서드 호출

  SqlSession session = sqlSessionFactory.openSession() 

 

20. 복붙

 

 

// findByDeptno 호출 

 

 

        a. 검색용 

              - 단일행 ( DTO 저장 )

<select id="" resultType="DeptDTO">
DeptDTO dto = session.selectOne("mapper id값");
// obj는 파라미터, mapper의 #{ } 에서 사용 
<select id="" resultType="DeptDTO" parameterType="obj타입">
DeptDTO dto = session.selectOne("mapper id값", Object obj);

 

             - 복수행 ( 여러 DTO에 저장하고 자동으로 List에 저장 )

<select id="findAll" resultType="DeptDTO">
=>	List<DeptDTO> list = session.selectList("mapper id값");


<select id="" resultType="DeptDTO" parameterType="obj타입">
=>	List<DeptDTO> list = session.selectList("mapper id값", Object obj);


<select id="findByDeptnoAndDname" resultType="DeptDTO" parameterType="hashmap">
=>	List<DeptDTO> list = session.selectList("mapper id값", HashMap map);
=> parameterType="값" 값이 정해져있다.


List<DeptDTO> list = session.selectList("mapper id값", Object obj, Rowbounds bounds);
=> 전체 레코드가 일정갯수만큼만 검색이 가능
=> new RowBounds (시작위치idx, 갯수)
=> paging 처리에서 주로 사용됨. (게시판)

 

 

 https://mybatis.org/mybatis-3/configuration.html

 

 

 

8. SqlSession close

session.close();

 

 

 

 

 

 

💻 코드


 

Configuration.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
        <property name="username" value="SCOTT"/>
        <property name="password" value="TIGER"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="DeptMapper.xml"/>
  </mappers>
</configuration>

 

 

DeptMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
  
<mapper namespace="DeptMapper">

  <select id="findAll" resultType="DeptDTO">
  	select deptno, dname, loc
  	from dept
  </select>
  
  <select id="findAllPage" resultType="DeptDTO">
  	select deptno, dname, loc
  	from dept
  	order by deptno
  </select>
  
  <select id="findByDeptno" resultType="DeptDTO" parameterType="int">
  	select deptno, dname, loc
  	from dept
  	where deptno = #{deptno}
  </select>
  
  <select id="findByDeptnoAndDname" resultType="DeptDTO" parameterType="DeptDTO">
  	select deptno, dname, loc
  	from dept
  	where deptno = #{deptno} or dname=#{dname}
  </select>
  
  
  
  <select id="findByDeptnoAndDnameMap" resultType="DeptDTO" parameterType="hashmap">
  	select deptno, dname, loc
  	from dept
  	where deptno = #{xxx} or dname=#{yyy}
  </select>
  
</mapper>

 

 

DeptDTO.java

//dept 테이블의 하나의 행(레코드)을 저장하는 용도
public class DeptDTO {
	
	// DeptDTO 클래스의 변수명은 dept테이블의 컬럼명과 동일하게 지정
	int deptno;  // dept테이블의 deptno 컬럼 저장
	String dname; // dept테이블의 dname 컬럼 저장
	String loc;  // dept테이블의 loc 컬럼 저장
	
	// 생성자
	public DeptDTO() {}

	public DeptDTO(int deptno, String dname, String loc) {
		this.deptno = deptno;
		this.dname = dname;
		this.loc = loc;
	}

	// getter, setter
	public int getDeptno() {
		return deptno;
	}

	public void setDeptno(int deptno) {
		this.deptno = deptno;
	}

	public String getDname() {
		return dname;
	}

	public void setDname(String dname) {
		this.dname = dname;
	}

	public String getLoc() {
		return loc;
	}

	public void setLoc(String loc) {
		this.loc = loc;
	}

	// toString()
	@Override
	public String toString() {
		return deptno+"\t"+dname+"\t"+loc;
	}
	
	
}

 

 

DeptMain.java

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class DeptMain {

	public static void main(String[] args) throws Exception {
		// Configuration.xml 파일 읽기
		
		String resource = "Configuration.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory =
		  new SqlSessionFactoryBuilder().build(inputStream);
		
		SqlSession session = sqlSessionFactory.openSession();

		// findByDeptno 호출
		DeptDTO dto = session.selectOne("DeptMapper.findByDeptno", 10);
		System.out.println(dto);
		
		// findAll 호출
		List<DeptDTO> list = session.selectList("DeptMapper.findAll");
		for (DeptDTO xxx : list) {
			System.out.println(xxx);
		}
		System.out.println("##########################################");
		
		
		// findByDeptnoAndDname
		DeptDTO dto2 = new DeptDTO();    // 파라미터를 dto2에 넣어주는 작업
		dto2.setDeptno(10);
		dto2.setDname("인사");
		List<DeptDTO> list2 = session.selectList("DeptMapper.findByDeptnoAndDname", dto2);
		for (DeptDTO xxx : list2) {
			System.out.println(xxx);
		}
		System.out.println("##########################################");

		
		// findByDeptnoAndDnameMap
		HashMap<String, Object> map =     // 두 개를 다 받아줘야하니까 object로
				new HashMap<>();     
		map.put("xxx", 10);
		map.put("yyy", "인사");
		
		List<DeptDTO> list3 = session.selectList("DeptMapper.findByDeptnoAndDnameMap", map);
		for (DeptDTO xxx : list3) {
			System.out.println(xxx);
		}
		System.out.println("##########################################");
		
		
		// findAllPage
		RowBounds bounds = new RowBounds(1, 3);
		List<DeptDTO> list4 = session.selectList("DeptMapper.findAllPage", null, bounds);
		for (DeptDTO xxx : list4) {
			System.out.println(xxx);
		}
		
		session.close();
	}

}

 

 

 

 

 

📌 결과


 

 

'DB > MyBatis' 카테고리의 다른 글

Mybatis - 조건문  (0) 2023.08.07
Mybatis - Dynamic SQL  (0) 2023.08.07
트랜잭션(Transaction) 처리  (0) 2023.08.03
DAO(Data Access Object) Pattern  (0) 2023.08.02
JDBC  (0) 2023.08.01
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
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
글 보관함