Skip to content

Commit d7dcb48

Browse files
authored
Merge pull request #2784 from awxiaoxian2020/convert-md-en
Convert the doc format to Markdown for en
2 parents 1ff4a86 + 06fae43 commit d7dcb48

17 files changed

+3689
-7079
lines changed

src/site/markdown/configuration.md

+778
Large diffs are not rendered by default.

src/site/markdown/dynamic-sql.md

+286
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,286 @@
1+
title: MyBatis 3 | Dynamic SQL
2+
author: Clinton Begin
3+
4+
## Dynamic SQL
5+
6+
One of the most powerful features of MyBatis has always been its Dynamic SQL capabilities. If you have any experience with JDBC or any similar framework, you understand how painful it is to conditionally concatenate strings of SQL together, making sure not to forget spaces or to omit a comma at the end of a list of columns. Dynamic SQL can be downright painful to deal with.
7+
8+
While working with Dynamic SQL will never be a party, MyBatis certainly improves the situation with a powerful Dynamic SQL language that can be used within any mapped SQL statement.
9+
10+
The Dynamic SQL elements should be familiar to anyone who has used JSTL or any similar XML based text processors. In previous versions of MyBatis, there were a lot of elements to know and understand. MyBatis 3 greatly improves upon this, and now there are less than half of those elements to work with. MyBatis employs powerful OGNL based expressions to eliminate most of the other elements:
11+
12+
- if
13+
- choose (when, otherwise)
14+
- trim (where, set)
15+
- foreach
16+
17+
### if
18+
19+
The most common thing to do in dynamic SQL is conditionally include a part of a where clause. For example:
20+
21+
```xml
22+
<select id="findActiveBlogWithTitleLike"
23+
resultType="Blog">
24+
SELECT * FROM BLOG
25+
WHERE state = ‘ACTIVE’
26+
<if test="title != null">
27+
AND title like #{title}
28+
</if>
29+
</select>
30+
```
31+
32+
This statement would provide an optional text search type of functionality. If you passed in no title, then all active Blogs would be returned. But if you do pass in a title, it will look for a title like that (for the keen eyed, yes in this case your parameter value would need to include any masking or wildcard characters).
33+
34+
What if we wanted to optionally search by title and author? First, I’d change the name of the statement to make more sense. Then simply add another condition.
35+
36+
```xml
37+
<select id="findActiveBlogLike"
38+
resultType="Blog">
39+
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
40+
<if test="title != null">
41+
AND title like #{title}
42+
</if>
43+
<if test="author != null and author.name != null">
44+
AND author_name like #{author.name}
45+
</if>
46+
</select>
47+
```
48+
49+
### choose, when, otherwise
50+
51+
Sometimes we don’t want all of the conditionals to apply, instead we want to choose only one case among many options. Similar to a switch statement in Java, MyBatis offers a choose element.
52+
53+
Let’s use the example above, but now let’s search only on title if one is provided, then only by author if one is provided. If neither is provided, let’s only return featured blogs (perhaps a strategically list selected by administrators, instead of returning a huge meaningless list of random blogs).
54+
55+
```xml
56+
<select id="findActiveBlogLike"
57+
resultType="Blog">
58+
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
59+
<choose>
60+
<when test="title != null">
61+
AND title like #{title}
62+
</when>
63+
<when test="author != null and author.name != null">
64+
AND author_name like #{author.name}
65+
</when>
66+
<otherwise>
67+
AND featured = 1
68+
</otherwise>
69+
</choose>
70+
</select>
71+
```
72+
73+
### trim, where, set
74+
75+
The previous examples have been conveniently dancing around a notorious dynamic SQL challenge. Consider what would happen if we return to our "if" example, but this time we make "ACTIVE = 1" a dynamic condition as well.
76+
77+
```xml
78+
<select id="findActiveBlogLike"
79+
resultType="Blog">
80+
SELECT * FROM BLOG
81+
WHERE
82+
<if test="state != null">
83+
state = #{state}
84+
</if>
85+
<if test="title != null">
86+
AND title like #{title}
87+
</if>
88+
<if test="author != null and author.name != null">
89+
AND author_name like #{author.name}
90+
</if>
91+
</select>
92+
```
93+
94+
What happens if none of the conditions are met? You would end up with SQL that looked like this:
95+
96+
```sql
97+
SELECT * FROM BLOG
98+
WHERE
99+
```
100+
101+
This would fail. What if only the second condition was met? You would end up with SQL that looked like this:
102+
103+
```sql
104+
SELECT * FROM BLOG
105+
WHERE
106+
AND title like ‘someTitle’
107+
```
108+
109+
This would also fail. This problem is not easily solved with conditionals, and if you’ve ever had to write it, then you likely never want to do so again.
110+
111+
MyBatis has a simple answer that will likely work in 90% of the cases. And in cases where it doesn’t, you can customize it so that it does. With one simple change, everything works fine:
112+
113+
```xml
114+
<select id="findActiveBlogLike"
115+
resultType="Blog">
116+
SELECT * FROM BLOG
117+
<where>
118+
<if test="state != null">
119+
state = #{state}
120+
</if>
121+
<if test="title != null">
122+
AND title like #{title}
123+
</if>
124+
<if test="author != null and author.name != null">
125+
AND author_name like #{author.name}
126+
</if>
127+
</where>
128+
</select>
129+
```
130+
131+
The *where* element knows to only insert "WHERE" if there is any content returned by the containing tags. Furthermore, if that content begins with "AND" or "OR", it knows to strip it off.
132+
133+
If the *where* element does not behave exactly as you like, you can customize it by defining your own trim element. For example, the trim equivalent to the *where* element is:
134+
135+
```xml
136+
<trim prefix="WHERE" prefixOverrides="AND |OR ">
137+
...
138+
</trim>
139+
```
140+
141+
The *prefixOverrides* attribute takes a pipe delimited list of text to override, where whitespace <u>is</u> relevant. The result is the removal of anything specified in the *prefixOverrides* attribute, and the insertion of anything in the *prefix* attribute.
142+
143+
There is a similar solution for dynamic update statements called *set*. The *set* element can be used to dynamically include columns to update, and leave out others. For example:
144+
145+
```xml
146+
<update id="updateAuthorIfNecessary">
147+
update Author
148+
<set>
149+
<if test="username != null">username=#{username},</if>
150+
<if test="password != null">password=#{password},</if>
151+
<if test="email != null">email=#{email},</if>
152+
<if test="bio != null">bio=#{bio}</if>
153+
</set>
154+
where id=#{id}
155+
</update>
156+
```
157+
158+
Here, the *set* element will dynamically prepend the SET keyword, and also eliminate any extraneous commas that might trail the value assignments after the conditions are applied.
159+
160+
Alternatively, you can achieve the same effect by using *trim* element:
161+
162+
```xml
163+
<trim prefix="SET" suffixOverrides=",">
164+
...
165+
</trim>
166+
```
167+
168+
Notice that in this case we’re overriding a suffix, while we’re still appending a prefix.
169+
170+
### foreach
171+
172+
Another common necessity for dynamic SQL is the need to iterate over a collection, often to build an IN condition. For example:
173+
174+
```xml
175+
<select id="selectPostIn" resultType="domain.blog.Post">
176+
SELECT *
177+
FROM POST P
178+
<where>
179+
<foreach item="item" index="index" collection="list"
180+
open="ID in (" separator="," close=")" nullable="true">
181+
#{item}
182+
</foreach>
183+
</where>
184+
</select>
185+
```
186+
187+
The *foreach* element is very powerful, and allows you to specify a collection, declare item and index variables that can be used inside the body of the element. It also allows you to specify opening and closing strings, and add a separator to place in between iterations. The element is smart in that it won’t accidentally append extra separators.
188+
189+
<span class="label important">NOTE</span> You can pass any Iterable object (for example List, Set, etc.), as well as any Map or Array object to foreach as collection parameter. When using an Iterable or Array, index will be the number of current iteration and value item will be the element retrieved in this iteration. When using a Map (or Collection of Map.Entry objects), index will be the key object and item will be the value object.
190+
191+
This wraps up the discussion regarding the XML configuration file and XML mapping files. The next section will discuss the Java API in detail, so that you can get the most out of the mappings that you’ve created.
192+
193+
### script
194+
195+
For using dynamic SQL in annotated mapper class, *script* element can be used. For example:
196+
197+
```java
198+
@Update({"<script>",
199+
"update Author",
200+
" <set>",
201+
" <if test='username != null'>username=#{username},</if>",
202+
" <if test='password != null'>password=#{password},</if>",
203+
" <if test='email != null'>email=#{email},</if>",
204+
" <if test='bio != null'>bio=#{bio}</if>",
205+
" </set>",
206+
"where id=#{id}",
207+
"</script>"})
208+
void updateAuthorValues(Author author);
209+
```
210+
211+
### bind
212+
213+
The `bind` element lets you create a variable out of an OGNL expression and bind it to the context. For example:
214+
215+
```xml
216+
<select id="selectBlogsLike" resultType="Blog">
217+
<bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
218+
SELECT * FROM BLOG
219+
WHERE title LIKE #{pattern}
220+
</select>
221+
```
222+
223+
### Multi-db vendor support
224+
225+
If a databaseIdProvider was configured a "_databaseId" variable is available for dynamic code, so you can build different statements depending on database vendor. Have a look at the following example:
226+
227+
```xml
228+
<insert id="insert">
229+
<selectKey keyProperty="id" resultType="int" order="BEFORE">
230+
<if test="_databaseId == 'oracle'">
231+
select seq_users.nextval from dual
232+
</if>
233+
<if test="_databaseId == 'db2'">
234+
select nextval for seq_users from sysibm.sysdummy1"
235+
</if>
236+
</selectKey>
237+
insert into users values (#{id}, #{name})
238+
</insert>
239+
```
240+
241+
### Pluggable Scripting Languages For Dynamic SQL
242+
243+
Starting from version 3.2 MyBatis supports pluggable scripting languages, so you can plug a language driver and use that language to write your dynamic SQL queries.
244+
245+
You can plug a language by implementing the following interface:
246+
247+
```java
248+
public interface LanguageDriver {
249+
ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql);
250+
SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterType);
251+
SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType);
252+
}
253+
```
254+
255+
Once you have your custom language driver you can set it to be the default by configuring it in the mybatis-config.xml file:
256+
257+
```xml
258+
<typeAliases>
259+
<typeAlias type="org.sample.MyLanguageDriver" alias="myLanguage"/>
260+
</typeAliases>
261+
<settings>
262+
<setting name="defaultScriptingLanguage" value="myLanguage"/>
263+
</settings>
264+
```
265+
266+
Instead of changing the default, you can specify the language for an specific statement by adding the `lang` attribute as follows:
267+
268+
```xml
269+
<select id="selectBlog" lang="myLanguage">
270+
SELECT * FROM BLOG
271+
</select>
272+
```
273+
274+
Or, in the case you are using mappers, using the `@Lang` annotation:
275+
276+
```java
277+
public interface Mapper {
278+
@Lang(MyLanguageDriver.class)
279+
@Select("SELECT * FROM BLOG")
280+
List<Blog> selectBlog();
281+
}
282+
```
283+
284+
<span class="label important">NOTE</span> You can use Apache Velocity as your dynamic language. Have a look at the MyBatis-Velocity project for the details.
285+
286+
All the xml tags you have seen in the previous sections are provided by the default MyBatis language that is provided by the driver `org.apache.ibatis.scripting.xmltags.XmlLanguageDriver` which is aliased as `xml`.

0 commit comments

Comments
 (0)