[ MyBatis3 ] 동적 SQL

- MyBatis 의 가장 강력한 기능 중 하나는 동적 SQL 기능이다.

- MyBatis 다른 요소의 사용을 최대한 제거하기 위해 OGNL기반의 표현식을 가져왔다.

    • if
    • choose (when, otherwise)
    • trim (where, set)
    • foreach

* if

<select id = "aaaa" parameterType = "Blog" resultType = "Blog">

SELECT * FROM BLOG

WHERE state = "bbbb"

<if test="title != null">

AND title like #{title}

</if>

</select>


- 이 구문은 선택적으로 문자열 검색 기능을 제공한다.

- title 값이 없다면 모든 active상태의 Blog가 리턴될 것이고 title 값이 있다면 그 값과 비슷한 데이터를 찾게 될 것이다.

* choose, when , otherwise

- 종종 모든 조건을 원하는 대신 한가지 경우만 만족하는 경우를 원할 수 있다, 자바에서 swith문과 유사하다.

<select id = "aaa" parameterType ="Blog" resultType = "Blog">

SELECT * FROM BLOG WHERE state = 'ACTIVE'

<choose >

<when test = "title != null">

AND title like #{title}

</when>

<when test ="author != null and author.name != null">

AND author_name like #{author.name}

</when>

<otherwise>

AND featured = 1

</otherwise>

</choose>

</select>


- title 만으로 검색하고 author 가 있으면 그값으로 검색하고 둘다 제공하기 않는다면 featured 상태의 blog가 리턴된다.


* trim, where, set


위 예제에서 어떤 조건에도 해당하지 않는다면

SELECT * FROM BLOG

WHERE

처럼 나온것이고 sql문이 꼬이게 될 것이다.

<select id=”findActiveBlogLike”parameterType=”Blog” resultType=”Blog”>

SELECT * FROM BLOG

<where>

<if test=”state != null”>

state = #{state}

</if>

<if test=”title != null”>

AND title like #{title}

</if>

<if test=”author != null and author.name != null”>

AND title like #{author.name}

</if>

</where>

</select>

>> where 요소는 태그에 의해 컨텐츠가 리턴되면 필요할 경우 "WHERE" 을 추가한다.

만약 컨텐츠가 "AND" 나 "OR"로 시작한다면 삭제해버린다.


만약 where 요소가 기대처럼 동작을 하지 않는다면, trim 요소를 사용자 정의할 수 있다.


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

</trim>

>> override 속성은 오버라이드하는 텍스트의 목록을 제한한다.

결과는 override 속성에 명시된 것들을 지우고 with 속성에 명시된 것을 추가한다.


<update id ="updateAuthorIfNecessary" parameterType="domain.blog.Author">

update Author

<set>

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

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

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

</set>

where id = #{id}

</update>


>> 여기서 set 요소는 동적으로 SET 키워드를 붙이고 필요없는 콤마를 제거한다.

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

</trim>


* foreach


- 동적 SQL에서 공통적으로 필요한 것으 collection에 대한 반복처리를 하는 것이다. 종종 IN 조건을 사용하게 된다.

- foreach 요소는 매우 강력하고 collection을 명시하는 것을 허용한다.

- 요소내부에서 사용할 수 있는 item, index 두가지 변수를 선언한다.


- 열고 닫는 문자열로 명시할 수 있고 반복간에 둘 수 있는 구분자도 추가할 수 있다.

[ MyBatis3 ] SQL Map XML 파일(resultMap-3)

* collection

<collection property="posts" ofType="domain.blog.Post">

<id property = "id" column="post_id" />

<result property ="subject" column="post_subject" />

</collection>


- collection 요소는 관계를 파악하기 위해 작동한다.

- ofType : 자바빈 프로퍼티 타입과 collection 의 타입을 구분하기 위해 필요하다.

>> associations과 collections에서 내포의 단계혹은 조합에는 제한이 없다.


* discriminator


<discriminator javaType="int" column="draft">

<case vaule="1" resultType="DraftPost" />

</discriminator>


- 종종 하나의 데이터베이스 쿼리는 많고 다양한 데이터 타입의 결과를 리턴한다.

이 요소는 클래스상속관계를 포함하여 이러한 사항을 위해 고려됨

- discriminator 정의는 column 과 javaType 속성을 명시한다.

column은 MyBatis로 하여금 비교할 값을 찾을 것이다. javaType은 동일성 테스트와 같은 것을 실행하기 위해 필요

- 각각의 레코드를 가져와 draft값과 비교한다. 만약 비교값과 같은 경우가 생기면 명시된 resultMap을 사용 없다면 무시된다.

[ MyBatis3 ] SQL Map XML 파일(resultMap-2)

* id , result

<id property ="id" column="post_id" />

<result property="subject" column="post_subject" />


>> 결과 매핑의 기본적인 형태, id와 result 모두 한개의 칼럼을 한개의 프로퍼티나 간단한 데이터 타입의 필드에 매핑한다.


* constructor


<constructor>

<idArg column="id" javaType="int"/>

<arg column="username" javaType="String" />

</constructor>


- 프로퍼티가 데이터전송객체(DTO) 타입 클래스로 작동한다.

- MyBatis는 private 프로퍼티와 private 자바빈 프로퍼티를 지원하지만 많은 사람들은 생성자 주입을 선호한다.


* association

<association property="author" column="blog_author_id" javaType='Author">

<id property="id" column="author_id" />

<result property="username" column="author_username"/>

</association>


- association 요소는 "has-one" 타입의 관계를 이룬다.

- association 매핑은 다른 결과와 작동한다. 값을 가져오기 위해 대상 프로퍼티를 명시한다.

- MyBatis는 관계를 정의하는 두가지 방법을 제공한다.

  • 내포된(Nested) Select : 복잡한 타입을 리턴하는 다른 매핑된 SQL구문을 실행하는 방법
  • 내포된(Nested) Result : 조인된 결과물을 반복적으로 사용하여 내포된 결과매핑을 사용하는 방법

- 관계를 위한 내포된 Select

<resultMap id ="blogResult" type="Blog">

<association property ="author" column ="blog_author_id" javaType = "Author" select="selectAuthor" />

</resultMap>


<select id="selectBlog" parameterType ="int" resultMap="blogResult">

SELECT * FROM ……..

</select>


<select id= "selectAuthor: parameterType="int" resultType="Author">

SELECT * FROM …….

</select>


>> 두개의 select 구문중 하나는 Blog를 로드하고 다른하나는 Author를 로드한다.

Blog의 resultMap은 author 프로퍼티를 로드하기 위해 "selectAuthor" 구문을 사용한다.

다른 프로퍼티들은 칼럼과 프로퍼티명에 일치하는 것들로 자동으로 로드 될 것이다.


이 방법은 간단한 반면, 큰 데이터나 목록에는 제대로 작동하지 않을 것이다.

이 방법은 "N +1 Select문제"으로 알려진 문제점을 가진다.

- 레코드의 목록을 가져오기 위해 하나의 sql구문을 실행한다.("+1"에 해당)

- 리턴된 레코드별로, 각각의 상세데이터를 로드하기 위해 select구문을 실행한다.("N"에 해당)


- 관계를 위한 내포된 Result


<select id ="selectBlog" parameterType="int" resultMap="blogResult">

select

B.id as blog_id,

B.title as blog_title,

B.author_id as blog_author_id.

A.id as author_id,

A.username as author_username,

A.bio as author_bio

from Blog B left outer join Author A on B.author_id = A.id

where B.id = #{id}

</select>


<resultMap id="blogResult" type="Blog">

<id property ="blog_id" column="id" />

<result property="title" column="blog_title" />

<association property ="author" column="blog_author_id" javaType ="Author" resultMap="authorResult" />

</resultMap>


<resultMap id="authorResult" type="Author">

<id property="id" column="author_id" />

<result property="username" column="author_user_name" />

<result property="bio" author_id = "author_bio" />

</resultMap>


>> id 요소는 내포된 결과 매핑에서 매우 중요한 역할을 담당한다.

결과중 유일한 것을 찾아내기 위한 한개 이상의 프로퍼티를 명시해야 한다.

가능하면 결과중 유일한 것을 찾아낼수 있는 프로퍼티를 선택해야 한다

[ MyBatis3 ] SQL Map XML 파일(resultMap)

# resultMap

- MyBatis에서 가장 중요하고 강력한 요소이다. ResultSet에서 데이터를 가져올 때 작성되는 JDBC코드를 대부분 줄여주는 역할을 담당한다.

- 모든 칼럼의 값이 결과가 되는 간단한 구문에서는 HashMap에서 키 형태로 자동으로 매핑된다, 하지만 대부분의 경우 HashMap은 매우 좋은 도메인 모델이 되지는 못한다.

- 그래서 대부분 도메인모델로는 자바빈이나 POJO를 사용할 것이다.

- TypeAliases가 편리한 기능임을 기억해두는게 좋다. TypeAliases를 사용하면 타이핑 수를 줄일 수 있다.
<typeAlias type="com.someapp.model.User" alias="User"/>

<select id ="selectUsers" parameterType="int" resultType="User">
</select>

- 칼럼명이 프로퍼티명과 다르다면
  1. SQL 구문에 별칭을 지정

    <select id ="selectUsers" parameterType ="int" resultType ="User">
    select
    user_id as "id"
    user_name as "userName"
    from some_table
    </select>


  2. 명시적인 resultMap을 선언하는 방법

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

    <select id = "selectUsers" parameterType ="int" resultType ="userResultMap">
    select user_id, user_name
    from some_table
    </select>

- resultMap요소는 많은 하위 요소를 가진다. 다음은 resultMap요소의 개념적인 뷰이다.

  • constructor - 인스턴스화 되는 클래스의 생성자에 결과를 삽입하기 위해 사용
  • id - ID 결과, ID와 같은 결과는 전반적으로 성능을 향상시킴
  • result - 필드나 자바빈 프로퍼티에 삽입되는 일반적인 결과
  • association - 복잡한 타입의 연관관계; 많은 결과는 타입으로 나타난다.
  • collection - 복잡한 타입의 컬렉션
  • discriminator - 사용할 resultMap을 판단하기 위한 결과값을 사용

> 가장 좋은 형태는 매번 resultMap을 추가해서 빌드한다.

[ MyBatis3 ] SQL Map XML 파일(select, insert, update, delete, sql)

MyBatis의 가장 큰 장점은 매핑된 구문이다. 동일한 기능의 JDBC코드와 비교하면 아마도 95%이상 코드수가 감소하기도 한다.


# Select

- select 구문은 가장 많이 쓰는 요소이다. MyBatis는 데이터를 조회하고 그 결과를 매핑하는데 집중하고 있다.
  • MyBatis
<select id ="selectPerson" parameterType = "int" resultType = "hashmap">
SELECT * FROM PERSON WHERE ID = #{id}
</select>

  • JDBC
String selectPerson = "SELECT * FROM PERSON WHERE ID = ?";
PreparedStatement ps = comm.prepareStatment(selectPerson);
ps.setInt(1,id);

# insert, update, delete

* insert
<insert id ="insertAuthor" parameterType="domain.blog.Author">
insert into Author (id, username, password, email, bio)
values (#{id}, #{username}, #{password}, #{email}, #{bio})
</insert>
* update
<update id = "updateAuthor" parameterType="domain.blog.Author">
update Author set
username = #{username}
password =#{password}
email = #{email}
bio = #{bio}
where id = #{id}
</update>
* delete
<delete id = "deleteAuthor" parameterType="int">
delete from Author where id = #{id}
</delete>

* insert 자동생성키 설정(Autoincrement)

- 사용하는 데이터베이스가 자동생성키를 지원하는 경우
<insert id ="insertAuthor" parameterType="domain.blog.Author"
useGeneratedKeys = "true" keyProperty ="id">

- 자동생성키를 지원하지 않는 경우 (랜덤 ID 생성 -> 자동생성키와 비슷한 효과를 나타냄)
<insert id ="insertAuthor" parameterType="domain.blog.Author">
<selectKey keyProperty = "id" resultType ="int' order = "BEFORE">
select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1
</selectKey>

# Sql

- 이 요소는 다른 구문에서 재사용 가능한 SQL구문을 정의할 때 사용

<sql id = "userColumns">id, username, password</sql>

<select id = "selectUsers" parameterType ="int' resultType ="hashmap">
select <include refid = "userColumns"/>
from some_table
where id = #{id}
</select>


※ 출처 : Mybatis-3-User-Guide.pdf

[ MyBatis3 ] 매퍼설정 XML(typeHandlers, objectFactory, ...)

 typeHandlers


- MyBatis가 PreparedStatement에 파라미터를 세팅하고 ResultSet에서 값을 가져올때 마다, TypeeHandler는     적절한 자바타입의 값 을 가져오기 위해 사용된다.
- 지원하지 않거나 비표준인 경우 아래와 같이 오버라이드 하여 사용 가능 하다.
public class ExampleTypeHandler implements TypeHandler {
@Override
public Object getResult(ResultSet rs, String str) throws SQLException {
// TODO Auto-generated method stub
return rs.getString(str);
}

@Override
public Object getResult(CallableStatement cs, int i) throws SQLException {
// TODO Auto-generated method stub
return cs.getString(i);
}

@Override
public void setParameter(PreparedStatement ps, int i, Object obj, JdbcType type) throws SQLException {
// TODO Auto-generated method stub
ps.setString(i,(String)obj);
}
}

- MyBatis는 타입을 판단하기 위해 데이터베이스의 메타데이터를 보지 않는다. 그래서 파라미터와 결과에 정확한 타입핸들러를 매핑해야 한다.

# objectFactory

- 결과객체의 인스턴스를 만들기 위해 사용한다.

# plugins

- MyBatis는 매핑 구문을 실행하는 어느 시점에 호출을 가로챈다. 기본적으로 MyBatis는 메소드 호출을 가로채기 위한 플러그인을 허용한다.

설정파일 오버라이드하기 

플러그인을 사용해서 MyBatis핵심 행위를 변경하기 위해, Configuration 클래스 전체를 오버라이드 할 수 있다. 이 클래스를 확장하고 내부메소드를 오버라이드 하고, sqlSessionFactoryBuilder.build(myConfig) 메소드에 그 객체를 넣어주면 된다. 이 작업은 MyBatis에 큰 영향을 줄수 있으니 주의해서 해야한다.

# environments

- 여러개의 환경으로 설정 할 경우 사용
- 중요한 것은 다중환경을 설정할 수 있지만 SqlSessionFactory 인스턴스마다 한개씩만 사용할 수 있다는 것
=> 데이터베이스별로 하나의 SqlSessionFactory

<environments default="development">
<environment id="development">

<transactionManager type="JDBC"/>

<dataSource type="POOLED">

<property name="driver"value="${driver}"/>

<property name="url"value="${url}"/>

<property name="username"value="${username}"/>

<property name="password"value="${password}"/>

</dataSource>

</environment>

</environments > 

* transactionManager
  • JDBC - 이 설정은 간단하게 JDBC 커밋과 롤백을 처리하기 위해 사용된다. 트랜젝션의 스코프를 관리하기 위해 dataSource로 부터 커넥션을 가져온다.

  • MANAGED - 이 설정은 어떤 것도 하지 않는다. 대신 컨테이너가 트랜젝션의 모든 생명주기를 관리한다.

* dataSource

  • UNPOOLED - 매번 요청에 대해 커넥션을 열고 닫는 간단한 DataSource이다.
  • POOLED - 폴링이 적용된 JDBC 커넥션을 위한 구현체이다. Connection 인스턴스를 생성하기 위해 매번 초기화하는 것을 피하게 해준다
  • JNDI - 컨테이너에 따라 설정이 변경되며, JNDI컨텍스트를 참조한다.


[ MyBatis3 ] 매퍼설정 XML -1(Properties, Setting, typeAliases)

- MyBatis XML 설정파일은 다양한 Setting과 Properties를 가진다.

# Properties

- 외부로 옮길 수 있으며 자바프로퍼티 파일 인스턴스에 설정이 가능하고 properties 요소의 하위 요소에 둘수 도 있다.

<beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">

<propertyname="driverClassName"value="${jdbc.driverClassName}"/>

<propertyname="url"value="${jdbc.url}"/>

<propertyname="username"value="${jdbc.username}"/>

<propertyname="password"value="${jdbc.password}"/>

</bean>

위 예제에서는 username과 password는 properties 요소의 설정된 값으로 대체될 수 있다. driver와 url속성은 *.properties파일에 포함된 값으로 대체할 수 있다. 이것은 설정에 대한 다양한 옵션을 제공하는 셈이다.

-속성이 한개 이상 존재한다면, MyBatis는 일정한 순서로 로드 한다.

  • properties 요소에 명시된 속성을 가장 먼저 읽는다.
  • properties 요소의 클래스 패스 자원이나 url속성으로부터 로드된 속성을 두번째로 읽는다.
  • 마지막으로 메소드 파라미터로 전달된 속성을 읽는다.

그래서 가장 우선순위가 높은 속성은 메서드의 파라미터로 전달된 값이고 그 다음은 자원및 url속성이고 마지막은 properties요소에 명시된 값이다.

# Setting

- 런타임시 MyBatis의 행위를 조정하기 위한 중요값들이다. 다음표는 셋팅값들의 의미와 디폴드 값을 정리한 것이다.

 

 

# typeAliases

- 타입 별칭은 자바타입에 대한 좀더 짧은 이름이다. 오직 XML설정에서만 사용되며, 타이핑을 줄이기 위해 존재한다.

- 공통의 자바타입에 대해서는 내장된 타입별칭이 있다. 모두 대소문자를 가린다.

 

 

※ 출처 : Mybatis-3-User_Guide.pdf 

MVC

MVC(Model , View, Controller)

Model      
- 실제 일처리하는 것  (Service : 연산, Repository : DB접근)
View      
- 눈에 보이는 화면     
Controller     
- Request / Response

서버 작업 순서

Request --> Controller --> Model --> Controller --> View