안녕로봇

블로그 이미지

안녕로봇

'mybatis'에 해당되는 글 3건

제목 날짜
  • 마이바티스 selectkey 2017.04.19
  • 동적 SQL 2017.03.29
  • mybatis 란? 2017.03.29

마이바티스 selectkey

mybatis 2017. 4. 19. 09:15


마이바티스 - selectKey


위 문장 해석

1. Products 테이블에 insert전(오라클 기준. order="BEFORE")


2. products_seq 시퀀스로 부터 생성된 식별값을 가져와서

- 생성된 값은 int 형태이며 (resultType="int") 

- ProductVO의 멤버변수인 productNo에 세팅하고(keyProperty="productNo")


3. Products 테이블 values부분 #{productsNo}에 

   방금 위에서 세팅된 값이 들어가게 되서 insert 처리 된다.

저작자표시 비영리 변경금지 (새창열림)

'mybatis' 카테고리의 다른 글

동적 SQL  (0) 2017.03.29
mybatis 란?  (0) 2017.03.29
Posted by 안녕로봇

동적 SQL

mybatis 2017. 3. 29. 19:45

동적 SQL

- SQL문에서 여러가지 분기처리를 위한 작업

- 파라미터 타입은 Map이나 클래스(VO, DTO 같은...)로 설정해야 한다!!


if 엘리먼트

 ex)

<select id="selectCommentByCondition" parameterType="hashmap" resultType="Comment">

SELECT comment_no, user_id, comment_content, reg_date FROM comment2

<if test="commentNo != null">

WHERE comment_no = #{commentNo} <--! 이때 commentNo는 해쉬맵의 키이고 해당하는 값을 가져옴-->

</if>

</select>


choose(when, otherwise) 엘리먼트

 ex)

<select id="selectCommentByConditionChoose" parameterType="hashmap" resultType="Comment">

SELECT comment_no, user_id, comment_content, reg_date

FROM comment2

<choose>

<when test="commentNo != null">

WHERE comment_no = #{commentNo}

</when>

<when test="user != null and user.userId != null">

WHERE user_id = #{user.userId}

</when>

<otherwise>

WHERE comment_no = 1

AND user_id = 'fromm0'

</otherwise>

</choose>

</select>


trim 엘리먼트

구문이 꼬이는걸 방지시켜준다 - (if문으로 쓸경우 where가 두번 나오거나 마지막 부분에 ,가 찍히는등)

where을 붙여주거나 AND, OR을 지워주거나 등등

ex)

<select id="selectCommentByConditionIf" parameterType="hashmap" resultType="Comment">

SELECT comment_no, user_id, comment_content, reg_date

FROM comment2

<where>

<if test="commentNo != null">

comment_no = #{commentNo}

</if>

<if test="user != null and user.userId != null">

AND user_id = #{user.userId}        ->> 앞쪽 if문이 null값인 경우 AND는 사라지고 where가 붙음

</if>

</where>

</select>


또는


<trim prefix="WHERE" prefixOverrides="AND |OR ">

<if test="commentNo != null">

AND comment_no = #{commentNo}

</if>

<if test="user != null and user.userId != null">

AND user_id = #{user.userId}

</if>

</trim>



trim 엘리먼트가 제공하는 속성

- prefix: 처리 후 엘리먼트 내용이 있으면 가장 앞에 붙여준다 (where같은거)

- prefixOverrides: 처리후 엘리먼트 내용 가장 앞에 해당 문자가 있다면 지워줌 (and 등)

- suffix: 처리 후 엘리먼트 내용이 있으면 가장 뒤에 붙여줌 (콤마같은거)

- suffixOverrides: 처리후 엘리먼트 내용 가장뒤에 해당문자가 있으면 지워줌 (콤마 같은거)


ex)

UPDATE comment2

<trim prefix="SET" suffixOverrides=",">

<if test="commentContent != null">comment_content = #{commentContent}, </if>

<if test="regDate != null">reg_date = #{regDate}</if>

</trim>

WHERE comment_no = #{commentNo};


foreach 엘리먼트

ex)

long[] cmtNos={1L,2L,3L};

HashMap<String,Object> hmap= new HashMap<String,Object>();

hmap.put(“commentNos”, cmtNos);


<select id="selectCommentByConditionForeach" parameterType="hashmap" resultType="Comment">

SELECT comment_no, user_id, comment_content, reg_date

FROM comment2

<trim prefix="WHERE" prefixOverrides="AND |OR "> <--! 빠져도 되는게 아닌지?? -->

<if test="commentNos != null">

comment_no IN

<foreach collection="commentNos" item="commentNo"

index="index" open="(" close=")" separator=",">

#{commentNo}

</foreach>

</if>

</trim>

</select>


=> 완성된 구문

SELECT comment_no, user_id, comment_content, reg_date

FROM comment2

WHERE comment_no IN (1, 2, 3)

저작자표시 비영리 변경금지 (새창열림)

'mybatis' 카테고리의 다른 글

마이바티스 selectkey  (0) 2017.04.19
mybatis 란?  (0) 2017.03.29
Posted by 안녕로봇

mybatis 란?

mybatis 2017. 3. 29. 19:11

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
Posted by 안녕로봇
이전페이지 다음페이지
블로그 이미지

by 안녕로봇

공지사항

    최근...

  • 포스트
  • 댓글
  • 트랙백
  • 더 보기

태그

  • ajax
  • Serialize
  • 인터셉터
  • 시작
  • 핸들러
  • jQuery
  • 한글인코딩
  • 업로드
  • 파일
  • 에러
  • El
  • 페이징
  • 이벤트
  • 마이바티스
  • 스프링
  • 400에러
  • jsp
  • 스케쥴러
  • Sts
  • selectKey
  • tomcat
  • 어노테이션
  • 스프링 프레임워크
  • 설정
  • 서버
  • css
  • mybatis
  • 표현언어
  • ClassNotFoundException
  • Spring

글 보관함

«   2025/11   »
일 월 화 수 목 금 토
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30

링크

카테고리

학습 (27)
Spring (16)
Spring 에러 처리 (7)
mybatis (3)
JSP (3)
jQuery JavaScript (4)
HTML CSS (0)
Java (1)
자바 용어 정리 (1)
학습 내용 정리 (0)
실습 작성 및 비교 (0)
Oracle (0)
오라클 용어 정리 (0)
학습 내용 정리 (0)

카운터

Total
Today
Yesterday
방명록 : 관리자 : 글쓰기
안녕로봇's Blog is powered by daumkakao
Skin info material T Mark3 by 뭐하라
favicon

안녕로봇

  • 태그
  • 링크 추가
  • 방명록

관리자 메뉴

  • 관리자 모드
  • 글쓰기
  • 학습 (27)
    • Spring (16)
      • Spring 에러 처리 (7)
    • mybatis (3)
    • JSP (3)
    • jQuery JavaScript (4)
    • HTML CSS (0)
    • Java (1)
      • 자바 용어 정리 (1)
      • 학습 내용 정리 (0)
      • 실습 작성 및 비교 (0)
    • Oracle (0)
      • 오라클 용어 정리 (0)
      • 학습 내용 정리 (0)

카테고리

PC화면 보기 티스토리 Daum

티스토리툴바