killog님 블로그를 참고하여 작성하였습니다. 출처 : https://kils-log-of-develop.tistory.com/576
Mybatis
Mybatis는 xml기반의 프레임워크였다. MyBatis 3에서는 새 옵션을 사용할 수 있다. MyBatis 3는 포괄적이고 강력한 Java 기반 구성 API를 기반으로 한다. 이 구성 API는 새로운 annotation 기반 구성뿐만 아니라 XML 기반 MyBatis 구성의 기초이다. annotation을 사용하면 많은 오버헤드를 발생시키지 않고 간단한 매핑된 문을 구현할 수 있다.
mybais-spring-boot-autoconfigure
autoconfigure를 사용하게 되면 mybatis 에플리케이션을 빠르게 build 할 수 있다.
장점
- 독립 실행형 응용프로그램 구축
- 상용구를 거의 0으로 줄임
- XML 구성 감소
단점
- query를 수정하게 되면 재컴파일 하게 된다.
- 제한적이다.
- 복잡한 문장에 대해서는 더 복잡하다.
@mapper
- Database를 자동으로 감지해 준다.
- SqlSessionFactory를 전달 하는 인스턴스를 자동 생성/등록한다.
- DataSource.SqlSessionFactoryBean의 인스턴스를 만들고 등록한다.
- @Mapper주석이 표시된 mapper를 자동 스캔하고 연결한다.
- SqlSessionTemplateSpring 컨텍스트에 등록하여 Bean에 주입 할 수 있도록 해준다
설정
maven or gradle 설정을 해주고 mapper만 작성해 준다면 문제없이 사용할 수 있다.
프로젝트 구조
src
-main
-java
-com
-example
-user
-UserController
-UserService
-UserDto
-UserMapper
maven
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
gradle
dependencies {
compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.0")
}
mapper
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Insert;
import com.example.user.UserDto;
@Mapper
public interface UserMapper {
@Select("SELECT user_idx, user_name, uesr_age FROM user_table ")
List<UserDto> userList(UserDto userDto);
// insert 후 index값 가져오기
@Insert(" INSERT INTO user_table(user_idx, user_name, user_age) "
+ " VALUES (0, #{user_name}, #{user_age}) ")
@Options(useGeneratedKeys = true, keyProperty = "idx")
int userInsert(UserDto userdto);
}
Dynamic SQL
동적 SQL을 사용하고 싶을 때 <script>를 사용하면 동적 SQL을 사용할 수 있다.
@Update({"<script>",
"update Author",
" <set>",
" <if test='username != null'>username=#{username},</if>",
" <if test='password != null'>password=#{password},</if>",
" <if test='email != null'>email=#{email},</if>",
" <if test='bio != null'>bio=#{bio}</if>",
" </set>",
"where id=#{id}",
"</script>"})
void updateAuthorValues(Author author);