minlog
article thumbnail


앞에서 DB와 관련하여 Connection pool과 Mybatis를 연동했다.
Mybatis가 어떻게 사용되는지 자세하게 정리하려고 한다.
 
 

Mybatis Api

자바객체와 SQL문을 자동으로 연동해주는 역할을 하는 ORM 프레임워크이다. 

sql문을 xml 또는 @어노테이션을 통해 작성하고 관리할 수 있다.

 

  • 복잡한 jdbc 코드 작성의 불편함을 해소해준다.
  • 쿼리 결과에 대한 맵핑 부분을 대신 해준다. 
  • 다양한 프로그랭 언어로 구현이가능하다.

 

 

Mybatis 를 활용하여 SQL문을 관리하는 프로세스

Mybatis 는 쿼리 매핑 구문을 실행하기 위해 sqlSession 객체를 사용한다.

 

*SqlSessionFactoryBuilder : Mybatis 설정 파일을 바탕으로 SqlSessionFactory 객체를 생성

* SqlSessionFactory :  sqlSession 객체를 생성.

* SqlSessionFactoryBean : 개발자가 설정하는 데이터소스와 연결해준다.

* SqlSession : 쿼리 매핑 구문을 실행하기 위해 사용된다. sqlSessionFactory로부터 생성됨.

 

[ 생성 및 연결 순서 ]

 

 

Mybatis Api 사용방법

 

1. 📑root-context.xml 에서 위치 설정

 

<mybatis-spring:scan base-package="kr.board.mapper"/>

설정한 패키지 위치의 @Mapper를 찾는다.

 

2. 클레스에  @Mapper 어노테이션 선언.

 
📑 BoardMapper.java

package kr.board.mapper;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface BoardMapper { 
	...
}

 
 
 

3. SQL문 작성 방법

 

SQL문 작성 방법에는 두 가지가 있다.
두 가지다 혼용하여 사용할 수 있지만, 한 가지 메서드에 두 가지 방법을 다 선언해 줄 수는 없다.
 

1)  xml 방식 

자바 파일 명과 xml 파일 명을 동일하게 일치 시켜준다.

 

📑 BoardMapper.java

public List<Board> getLists();
public void boardInsert(Board vo);	
public Board boardContet(int idx);
public void boardDelete(int idx);
public void boardUpdate(Board vo);

 
 
📑 BoardMapper.xml
 
- <mapper namespace= "kr.board.mapper.BoardMapper">  연결되는 java 객체를 넣어준다.
- <mapper> 태그 안에 <select>  또는 <update> 태그로 쿼리문을 넣어준다. 

  • <select>  : 전체 조회, 생성, 삭제  
  • <update> : 수정

 
- 쿼리문을 감싸는 <select> 또는 <update> 태그의 id = 메서드 명이다.
- 쿼리문을 감싸는 <select> 또는 <update> 태그의 resultType = 결과 값은 VO 객체 ( entity )이다. 
- 마이바티스 쿼리문은 '#'을 사용한다.  #{ 컬럼명 } ○   ${ 컬럼명 }   X
 

<?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= "kr.board.mapper.BoardMapper">

	<select id="getLists" resultType="kr.board.entity.Board">
		select * from myboard order by idx desc
	</select>
	<!-- mybatis 는 파라미터 #{} -->
	<select id="boardInsert" resultType="kr.board.entity.Board">
		insert into myboard(title,content,writer) 
		values(#{title},#{content},#{writer}) 	
	</select>
	<select id="boardContet" resultType="kr.board.entity.Board">
		select * from myboard where idx=#{idx}
	</select>
	<select id="boardDelete" parameterType="int" resultType="kr.board.entity.Board">
		delete from myboard where idx=#{idx}
	</select>
	<update id="boardUpdate" parameterType="kr.board.entity.Board">
		update myboard set title=#{title}, content=#{content}
		where idx=#{idx}
	</update>
</mapper>

 
 

2. 마이바티스에서 제공해주는 api @어노테이션 방식

- xml 파일이 없어도 된다.
- @Update("쿼리문") , @Select("쿼리문") , @Delete("쿼리문"), @Insert("쿼리문")
 
📑 BoardMapper.java

@Update("update myboard set count=count+1 where idx=#{idx}")
public void boardCount(int idx);

 
 
 
 

profile

minlog

@jimin-log

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!