mybatis 란?
mybatis
- 더 빠른 JDBC 코딩을 위한 일반화된 프레임워크
- DB작업을 간편하게 해줌!
- SQL문은 별도의 XML 파일로 관리함: 신속 수정, 유지보수성이 향상!
프로젝트에서 mybatis 사용설정
mybatis.properties - DB접속설정 관련 파일
mybatis-config.xml
- <properties resource="mybatis.properties">설정 내용 수정 또는 추가해주기
ex) username/javauser password/javauser123
- <setting name="mapUnderscoreToCamelCase" value="true" />
DB 테이블의 컬럼명이 _ 언더바가 들어가고 빈의 멤버변수(프로퍼티)가 낙타표기법으로 만들어져 있을때
이 옵션을 true값으로 주면 자동으로 변환해서 맵핑 처리해줌
- 타입별칭: 기본 자료형 외에 자료형에 대해서 맵핑 처리
ex)
<typeAliases>
<typeAlias type="com.springweb.pd.model.PdDTO" alias="PdDTO" />
<typeAlias type="com.springweb.pd.model.CommnetVO" alias="CommnetVO" />
</typeAliases>
AbstractRepository (mybatis 객체 생성하기)
- mybatis-config.xml 설정 파일을 읽어서 mybatis 객체를 생성
- sqlSessionFactory 객체: mybatis의 전반적인 정보를 가지고 제어. 애플리케이션 내에서 한개만 생성!
매퍼 XML 추가
ex) pd.xml
파라미터 표기법
- #{commentNo}
트랜잭션 관리
- mybatis를 사용할 때 중요한 객체는 SqlSessionFactory 객체,
각각의 세부 작업은 SqlSessionFactory 에서 만들어지는 SqlSession 객체가 담당
- openSession() 메서드를 호출하면 트랜잭션이 이와 동시에 명시적으로 시작
- SqlSession 클래스의 메서드 commit(), rollback()
- 스프링 연동 모듈을 사용시 트랜잭션에 대한 제어는 마이바티스가 담당하지 않고, 스프링에 위임
매퍼 XML
<mapper namespace="com.mybatis.mapper.pd">
매핑구문
<insert id="insertPd" parameterType="PdDTO">
<selectKey keyProperty="no" resultType="int" order="BEFORE">
select PD_SEQ.nextval from dual
</selectKey>
insert into pd values(#{no}, #{pdName}, #{price}, sysdate)
</insert>
~~~~</mapper>
매퍼 XML을 구성하는 엘리먼트들
- resultMap
ex)
<resultMap id="baseResultMap" type="Comment">
<id column="comment_no" jdbcType="BIGINT" property="commentNo" />
<result column="user_id" jdbcType="VARCHAR" property="userId" />
<result column="reg_date" jdbcType="TIMESTAMP" property="regDate" />
<result column="comment_content" jdbcType="VARCHAR" property="commentContent" />
</resultMap>
<select id="selectCommentByPrimaryKey" parameterType="long" resultMap="baseResultMap">
SELECT comment_no, user_id, comment_content, reg_date FROM comment2
WHERE comment_no = #{commentNo}
</select>
- sql
각각의 매핑 구문에서 공통으로 사용할 수 있는 SQL 문자열의 일부를 정의하고 재사용
ex)
<sql id="BaseColumns">
comment_no AS commentNo, user_id AS userId,
comment_content AS commentContent, reg_date AS regDate
</sql>
<select id="selectCommentByPrimaryKey" parameterType="long" resultType="ldg.mybatis.model.Comment">
SELECT
<include refid="BaseColumns"/> 자주 반복되는 부분 인클루드 시킴!
FROM comment2 WHERE comment_no = #{commentNo}
</select>
- insert, update, delete, select
ex)
<insert id="insertComment" parameterType="ldg.mybatis.model.Comment">
INSERT INTO comment2(comment_no, user_id, comment_content, reg_date)
VALUES (comment2_seq.nextval, #{userId}, #{commentContent}, #{regDate})
</insert>
<update id="updateComment" parameterType="ldg.mybatis.model.Comment">
UPDATE comment2 SET comment_content = #{commentContent}
WHERE comment_no = #{commentNo};
</update>
<delete id="deleteComment" parameterType="long">
DELETE FROM comment2
WHERE comment_no = #{commentNo};
</delete>
- selectKey
방금 입력한 자동 생성 키가 무슨 값인지 입력과 동시에 알아내기 위한 기능
ex)
<insert id="insertBoard" parameterType="boardVO">
<selectKey resultType="int" keyProperty="no" order="BEFORE">
<!--오라클은 시퀀스가 먼저라서 BEFORE-->
select board_seq.nextval as no from dual
</selectKey>
insert into board (no, name, pwd, title, email, content)
values(#{no},#{name},#{pwd},#{title},#{email}, #{content})
</insert>
'mybatis' 카테고리의 다른 글
마이바티스 selectkey (0) | 2017.04.19 |
---|---|
동적 SQL (0) | 2017.03.29 |