2020-11-12 TIL
3 minute read
Dynamic sql
- https://mybatis.org/mybatis-3/ko/dynamic-sql.html
조건에 따라 sql을 바꾸는 문법
choose
- 상호배타적이다.
- 하나의 조건이 선택되면 나머지는 배제된다.
- 상호배타적인 조건을 걸거라면 if 보다 낫다.
- 사용법
<select id="select21" resultMap="BoardMap" parameterType="map">
select
board_id,
title,
contents,
created_date,
view_count
from x_board
where
<choose>
<when test="item == 'no'">
board_id = #{keyword}
</when>
<when test='item == "title"'>
title like concat('%', #{keyword}, '%')
</when>
<otherwise>
contents like concat('%', #{keyword}, '%')
</otherwise>
</choose>
</select>
- ”””” 이나 ‘’’’ 은 불가능하다
- ”’’” 이나 ‘””’ 은 가능하다.
- 파라미터로 넘어오는 객체에서 해당 이름으로 값을 꺼내서 값과 문자열을 비교한다. 이때 문자열로 비교하고 싶을때는 “” 을 써야한다.
- 숫자일 경우에는 “’'”이 안된다.
- 문자일 경우에는 “’'”이 된다.
set
- set 태그는 set 이라는 sql 문을 만들면서 항목이 하나인데 앞이나 뒤에 , 가 있을 경우 , 를 자동으로 제거한다.
<update id="update4" parameterType="map">
update x_board
<set>
<if test="title != null">title=#{title},</if>
<if test="content != null">contents=#{content}</if>
</set>
where board_id=#{no}
</update>
foreach
- 값을 arrayList에 담아서 그 arrayList를 맵에 담아서 맵을 넘겨준다.
- where 태그가 앞뒤에 있는 or를 자동으로 제거한다.
ArrayList<Object> noList = new ArrayList<>();
for (String value : values) {
noList.add(value);
}
params.put("noList", noList);
- 빈문자열을 스플릿하면 빈문자열도 문자열로 취급해서 배열이 하나 생성되는 것이 된다.
<select id="select23" resultMap="BoardMap" parameterType="map">
select
board_id,
title,
contents,
created_date,
view_count
from x_board
<where>
<foreach collection="noList" item="no">
<if test="no != ''">
or board_id = #{no}
</if>
</foreach>
</where>
</select>
주석
<select id="select24" resultMap="BoardMap" parameterType="map">
select
board_id,
title,
contents,
created_date, <!-- xml, html 주석이라 sql 문을 만들때는 사라진다. -->
view_count /* sql 주석이기 때문에 포함되어 DB로 옮겨진다. */
from x_board
<where>
board_id in /* (1, 2, 11, 12) */
<foreach collection="noList" item="no" open="(" separator="," close=")">
#{no}
</foreach>
</where>
</select>
bind
<select id="select26" resultMap="BoardMap" parameterType="map">
<bind name="titlePattern" value="'%' + _parameter.title + '%'"/>
select
board_id,
title,
contents,
created_date,
view_count
from x_board
<where>
title like #{titlePattern}
</where>
</select>
</mapper>
sql
- 여러 sql 문에서 중복적으로 사용하는 sql 일부를 별도로 관리할 수 있다.
join 데이터 가져오기
<result column="contents" property="content"/>
<result column="created_date" property="registeredDate"/>
<result column="view_count" property="viewCount"/>
<collection property="files" ofType="AttachFile">
<id column="board_file_id" property="no"/>
<result column="file_path" property="filePath"/>
<result column="board_id" property="boardNo"/>
</collection>
+----------+-------+----------+---------------------+------------+---------------+-----------+
| board_id | title | contents | created_date | view_count | board_file_id | file_path |
+----------+-------+----------+---------------------+------------+---------------+-----------+
| 19 | ohora | hul | 2020-10-30 11:55:04 | 0 | 112 | 1.gif |
| 19 | ohora | hul | 2020-10-30 11:55:04 | 0 | 113 | 2.gif |
| 19 | ohora | hul | 2020-10-30 11:55:04 | 0 | 114 | 2.gif |
+----------+-------+----------+---------------------+------------+---------------+-----------+
3 rows in set (0.000 sec)
- new board()
- no - 19
- title - ohora
- content - hul
rs.next()
- files
- board_file_id 가 다르면 AttachFile을 만든다.
- new AttachFile(); - 112, a.gif, 19 - 200번지
- new AttachFile(); - 113, b.gif, 19 - 300번지
- new AttachFile(); - 114, b.gif, 19 - 400번지
- attachFile 을 files에 넣는데 files 는 list이다.
- new arraylist(2000번지)를 만들어서 순서대로 넣는다.
- 2000번지 에는 200번지 / 300번지 / 400번지 주소가 담긴다.
- board의 files에 2000번지 주소를 담는다.
DB 모델링
- 모델링? 시스템을 분석하고 구조화시켜 글과 그림으로 표현한 것.
- 렌더링? 명령어를 해석하여 화면에 출력하는 것.
- DB 모델링? 데이터를 분석하고 구조화시켜 데이터 속성과 관계를 글과 그림으로 펴현한 것.
- 목표? 데이터가 중복되지 않도록 테이블을 구조화하는 것
- 중복 데이터를 제거 -> 데이터의 안정성, 신뢰성을 높인다. -> 무결성을 유지한다.
- 주요 용어
- table(relation, entity)
- intension(schema)
- extention(instance, data)
- row(tupel, record)
- column(attribute, field)
- key
- 수퍼 키
- 데이터를 구분할 때 사용할 식별자.
- 한 개 이상의 데이터로 구성된다.
- 후보 키 = 최소 키
- 최소한의 컬럼 값만으로 식별이 가능한 키.
- 후보 키 중에 프라이머리 키를 선택한다.
- 기본 키 / 주 키
- 후보 키 중에서 데이터 식별자로 사용하기 위해 선정된 키
- 나머지 후보 키는 대인키로 불린다.
- 대리 키 / 인공 키
- 주 키의 컬럼의 개수가 많거나 주 키로 사용할 적절한 컬럼이 없는 경우, 일련 번호와 같은 임의의 컬럼을 추가하여 PK로 만든다.
- 외래 키
- 다른 테이블의 PK 값을 저장하는 컬럼
- FK가 있는 테이블을 자식 테이블이라 부르고,
- FK가 가리키는 테이블을 부모 테이블이라 부른다.
- 수퍼 키 > 후보 키 > 주 키 / 대안 키=유니크 컬럼