프로그래밍/스프링 MVC | 2014. 1. 22. 18:50
- MyBatis 의 가장 강력한 기능 중 하나는 동적 SQL 기능이다.
- MyBatis 다른 요소의 사용을 최대한 제거하기 위해 OGNL기반의 표현식을 가져왔다.
* 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) (0) | 2014.01.22 |
---|---|
[ MyBatis3 ] SQL Map XML 파일(resultMap-2) (0) | 2014.01.22 |
[ MyBatis3 ] SQL Map XML 파일(resultMap) (0) | 2014.01.22 |
[ MyBatis3 ] SQL Map XML 파일(select, insert, update, delete, sql) (0) | 2014.01.22 |
[ MyBatis3 ] 매퍼설정 XML(typeHandlers, objectFactory, ...) (0) | 2014.01.22 |
프로그래밍/스프링 MVC | 2014. 1. 22. 18:47
* 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 (0) | 2014.01.22 |
---|---|
[ MyBatis3 ] SQL Map XML 파일(resultMap-2) (0) | 2014.01.22 |
[ MyBatis3 ] SQL Map XML 파일(resultMap) (0) | 2014.01.22 |
[ MyBatis3 ] SQL Map XML 파일(select, insert, update, delete, sql) (0) | 2014.01.22 |
[ MyBatis3 ] 매퍼설정 XML(typeHandlers, objectFactory, ...) (0) | 2014.01.22 |
프로그래밍/스프링 MVC | 2014. 1. 22. 18:46
* 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는 관계를 정의하는 두가지 방법을 제공한다.
- 관계를 위한 내포된 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 (0) | 2014.01.22 |
---|---|
[ MyBatis3 ] SQL Map XML 파일(resultMap-3) (0) | 2014.01.22 |
[ MyBatis3 ] SQL Map XML 파일(resultMap) (0) | 2014.01.22 |
[ MyBatis3 ] SQL Map XML 파일(select, insert, update, delete, sql) (0) | 2014.01.22 |
[ MyBatis3 ] 매퍼설정 XML(typeHandlers, objectFactory, ...) (0) | 2014.01.22 |
프로그래밍/스프링 MVC | 2014. 1. 22. 18:45
# resultMap
- resultMap요소는 많은 하위 요소를 가진다. 다음은 resultMap요소의 개념적인 뷰이다.
> 가장 좋은 형태는 매번 resultMap을 추가해서 빌드한다.
[ MyBatis3 ] SQL Map XML 파일(resultMap-3) (0) | 2014.01.22 |
---|---|
[ MyBatis3 ] SQL Map XML 파일(resultMap-2) (0) | 2014.01.22 |
[ MyBatis3 ] SQL Map XML 파일(select, insert, update, delete, sql) (0) | 2014.01.22 |
[ MyBatis3 ] 매퍼설정 XML(typeHandlers, objectFactory, ...) (0) | 2014.01.22 |
[ MyBatis3 ] 매퍼설정 XML -1(Properties, Setting, typeAliases) (0) | 2014.01.22 |
프로그래밍/스프링 MVC | 2014. 1. 22. 18:44
- MyBatis의 가장 큰 장점은 매핑된 구문이다. 동일한 기능의 JDBC코드와 비교하면 아마도 95%이상 코드수가 감소하기도 한다.
※ 출처 : Mybatis-3-User-Guide.pdf
[ MyBatis3 ] SQL Map XML 파일(resultMap-2) (0) | 2014.01.22 |
---|---|
[ MyBatis3 ] SQL Map XML 파일(resultMap) (0) | 2014.01.22 |
[ MyBatis3 ] 매퍼설정 XML(typeHandlers, objectFactory, ...) (0) | 2014.01.22 |
[ MyBatis3 ] 매퍼설정 XML -1(Properties, Setting, typeAliases) (0) | 2014.01.22 |
MVC (0) | 2014.01.22 |
프로그래밍/스프링 MVC | 2014. 1. 22. 18:44
typeHandlers
설정파일 오버라이드하기 플러그인을 사용해서 MyBatis핵심 행위를 변경하기 위해, Configuration 클래스 전체를 오버라이드 할 수 있다. 이 클래스를 확장하고 내부메소드를 오버라이드 하고, sqlSessionFactoryBuilder.build(myConfig) 메소드에 그 객체를 넣어주면 된다. 이 작업은 MyBatis에 큰 영향을 줄수 있으니 주의해서 해야한다. |
<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>
[ MyBatis3 ] SQL Map XML 파일(resultMap-2) (0) | 2014.01.22 |
---|---|
[ MyBatis3 ] SQL Map XML 파일(resultMap) (0) | 2014.01.22 |
[ MyBatis3 ] SQL Map XML 파일(select, insert, update, delete, sql) (0) | 2014.01.22 |
[ MyBatis3 ] 매퍼설정 XML -1(Properties, Setting, typeAliases) (0) | 2014.01.22 |
MVC (0) | 2014.01.22 |
프로그래밍/스프링 MVC | 2014. 1. 22. 18:30
- 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는 일정한 순서로 로드 한다.
그래서 가장 우선순위가 높은 속성은 메서드의 파라미터로 전달된 값이고 그 다음은 자원및 url속성이고 마지막은 properties요소에 명시된 값이다.
# Setting
- 런타임시 MyBatis의 행위를 조정하기 위한 중요값들이다. 다음표는 셋팅값들의 의미와 디폴드 값을 정리한 것이다.
# typeAliases
- 타입 별칭은 자바타입에 대한 좀더 짧은 이름이다. 오직 XML설정에서만 사용되며, 타이핑을 줄이기 위해 존재한다.
- 공통의 자바타입에 대해서는 내장된 타입별칭이 있다. 모두 대소문자를 가린다.
※ 출처 : Mybatis-3-User_Guide.pdf
[ MyBatis3 ] SQL Map XML 파일(resultMap-2) (0) | 2014.01.22 |
---|---|
[ MyBatis3 ] SQL Map XML 파일(resultMap) (0) | 2014.01.22 |
[ MyBatis3 ] SQL Map XML 파일(select, insert, update, delete, sql) (0) | 2014.01.22 |
[ MyBatis3 ] 매퍼설정 XML(typeHandlers, objectFactory, ...) (0) | 2014.01.22 |
MVC (0) | 2014.01.22 |
프로그래밍/스프링 MVC | 2014. 1. 22. 16:30
MVC(Model , View, Controller)
Model
- 실제 일처리하는 것 (Service : 연산, Repository : DB접근)
View
- 눈에 보이는 화면
Controller
- Request / Response
서버 작업 순서
Request --> Controller --> Model --> Controller --> View
[ MyBatis3 ] SQL Map XML 파일(resultMap-2) (0) | 2014.01.22 |
---|---|
[ MyBatis3 ] SQL Map XML 파일(resultMap) (0) | 2014.01.22 |
[ MyBatis3 ] SQL Map XML 파일(select, insert, update, delete, sql) (0) | 2014.01.22 |
[ MyBatis3 ] 매퍼설정 XML(typeHandlers, objectFactory, ...) (0) | 2014.01.22 |
[ MyBatis3 ] 매퍼설정 XML -1(Properties, Setting, typeAliases) (0) | 2014.01.22 |
Recent Comments