반응형
MyBatis란 ?
: 자바 객체와 SQL문 사이의 자동 매핑을 지원하는 매퍼 프레임 워크이다.
MyBatis에서는 SQL 쿼리를 작성할 때 XML 또는 어노테이션을 이용해서 작업할 수 있다. 이를 통해 쿼리 구문을 작성하고 데이터 베이스와 통신을 수행할 수 있다. MyBatis는 매우 유연한 구조를 가지고 있어 SQL 쿼리와 자바 객체의 매핑 규칙을 세부적으로 지정할 수 있으며 동적 SQL 쿼리 구분을 작성할 수 있게 지원한다.
1. yml 파일에 MyBatis 설정하기
mybatis:
mapper-locations:
- classpath:mapper/**.xml
configuration:
map-underscore-to-camel-case: true
2. 의존 주입할 인터페이스에 @Mapper 어노테이션 선언하기
@Mapper // MyBatis 의존 설정함 (build.gradle 파일)
public interface UserRepository {
public int insert(User user);
public int updateById(User user);
public int deleteById(Integer id);
public User findById(Integer id);
public List<User> findAll();
}
3. 쿼리문을 써줄 xml 파일 생성
→ DB 접근 기술 DAO를 구현했다면 Mybatis는 xml 파일로 설정한다.
: 이점은 Connection, PreparedStatement, ResultSet을 알아서 관리 및 매핑해주고 close 처리를 자동으로 해준다.
user.xml 파일 예제
→ #{ }안은 자바에서 사용하기 때문에 자바에서 사용하는대로 적어야 한다.
mysql에서 쓰는 건 스네이크 케이스
<?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="com.tenco.bank.repository.interfaces.UserRepository">
// id 와 repository에 적은 변수명 같게 !
<insert id = "insert">
insert into user_tb (username, password, fullname, created_at)
values(#{username}, #{password}, #{fullname}, now())
</insert>
<update id = "updateById">
update user_tb set username = #{uesrname}, password = #{passoword},
fullname = #{fullname} where id = #{id}
</update>
<delete id = "deleteById">
delete from user_tb
where id = #{id}
</delete>
<select id = "findById" resultType = "com.tenco.bank.repository.model.User">
select * from user_tb where id = #{id}
</select>
<select id = "findByAll" resultType = "com.tenco.bank.repository.model.User">
select * from uesr_tb
</select>
</mapper>
반응형
'프로그래밍 > Spring Boot' 카테고리의 다른 글
Spring Boot_마이그레이션(migration) H2 데이터베이스 → MySQL 데이터베이스 (0) | 2023.04.21 |
---|---|
Spring Boot_예외 처리 기술 (Exception) (0) | 2023.04.18 |
Spring Boot_H2 DB 초기 설정 (0) | 2023.04.18 |
Spring Boot_인터셉터(Interceptor) (0) | 2023.04.13 |
Spring Boot_필터(Filter) (0) | 2023.04.13 |