카테고리 없음
mybatis sql 설정
당근개발자
2022. 2. 5. 15:26
application.properties 설정
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:todo
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
mybatis.config-location=classpath:mybatis/mybatis-config.xml
resources/mybatis/mybatis.config 파일 생성
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-http:////mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<mappers>
<mapper resource="mybatis/mapper/todo-mapper.xml"></mapper>
</mappers>
</configuration>
resources/mybatis/todo mapper.xml 생성
<?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.codepresso.todo.repository.TodoRepository">
<insert id="save">
INSERT INTO TODO(CONTENT, ISCOMPLETED)
VALUES (#{todo.content}, #{todo.isCompleted});
</insert>
// select는 resulttype을 명시해줘야함
<select id="select_all" resultType="com.codepresso.todo.vo.Todo">
select * from todo;
</select>
<delete id="delete_todo">
delete from ToDO where id = ${id};
</delete>
</mapper>
repository interface 생성
package com.codepresso.todo.repository;
import com.codepresso.todo.vo.Todo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.ArrayList;
import java.util.List;
@Mapper
public interface TodoRepository {
void save(@Param("todo") Todo todo);
List<Todo> select_all();
void delete_todo(@Param("id") Integer id);
}
mybatis #{} ${} 차이
#{}
쿼리문을 작성할 때 #{} 을 사용하는 경우 preparedStatement를 생성하게 되는데 ,
?에 파라미터가 바인딩되어 수행이된다.
이렇게 파싱된 쿼리문은 재활용(캐싱) 되기 때문에 효율적이다.
!! 쿼리주입을 예방 할 수있어 보안 측면에서 유리하다.
${}
값을 넣어진 채로 쿼리문이 수행된다. 그렇기 때문에, 파라미터 값이 바뀔때마다 항상 쿼리문 파싱을 진행해야한다.
성능 상의 단점이존재한다.
그리고 쿼리문의 #{} 을 사용한 것과 다르게 작은 따옴표 ('')가 붙지 않기 때문에 아래처럼 테이블 이름이나 컬럼 이름을
동적으로 결정할때 사용할 수있다.
테이블이나 컬럼명, 예약어르르 파라미터로 전달하고 싶을때 사용한다.