MyBatis - 기타 기능

박찬우·2024년 2월 6일

스프링 DB

목록 보기
36/53

애노테이션 사용

  • xml 대신 애노테이션에 SQL을 작성
  • @Insert , @Update , @Delete , @Select 기능이 제공된다.
  • 이 경우 XML에는 <select id="findById"> ~ </select> 는 제거해야 한다.
  • 동적 SQL이 해결되지 않으므로 간단한 경우에만 사용한다.
  • 참고 : https://mybatis.org/mybatis-3/ko/java-api.html
@Select("select id, item_name, price, quantity from item where id=#{id}") 
Optional<Item> findById(Long id);

문자열 대체(String Substitution)

  • 문자 그대로를 처리하고 싶은 경우 사용
  • 인젝션 공격을 당할 수 있음
  • ${}
@Select("select * from user where ${column} = #{value}") 
User findByColumn(@Param("column") String column, @Param("value") String value);

재사용 가능한 SQL 조각

<sql id="userColumns"> ${alias}.id,${alias}.username,${alias}.password </sql>

<select id="selectUsers" resultType="map">  
  select    
  <include refid="userColumns"><property name="alias" value="t1"/></include>,    <include refid="userColumns"><property name="alias" value="t2"/></include> 
  from some_table t1    
  cross join some_table t2 
</select>

Result Maps

<resultMap id="userResultMap" type="User">  
  <id property="id" column="user_id" />  
  <result property="username" column="user_name"/>  
  <result property="password" column="hashed_password"/> 
</resultMap>

<select id="selectUsers" resultMap="userResultMap"> 
  select user_id, user_name, hashed_password  
  from some_table  where id = #{id} 
</select>
profile
진짜 개발자가 되어보자

0개의 댓글