实体类与表字段不一致问题
<resultMap id="getStudentRm" type="com.hand.domain.Student">
<id property="id" column="s_id"/>
<result property="birth" column="s_birth"/>
<result property="name" column="s_name"/>
<result property="sex" column="s_sex"/>
</resultMap>
如果是多表查询的话
一对一
<resultMap id="teacherResultMap" type="com.hand.domain.Teacher">
<id column="t_id" property="t_id"/>
<result column="t_name" property="t_name"/>
<collection property="courses" ofType="com.hand.domain.Course">
<id column="c_id" property="c_id"/>
<result column="c_name" property="c_name"/>
</collection>
</resultMap>
<select id="selectTeacherAndCourse" resultMap="teacherResultMap" >
select t.t_id,t.t_name,c.c_id from teacher t
left join course c on t.t_id = c.t_id
where t.t_id = #{id}
</select>
一对多
<resultMap id="teacherResultMap" type="com.hand.domain.Teacher">
<id column="t_id" property="t_id"/>
<result column="t_name" property="t_name"/>
<collection property="courses" ofType="com.hand.domain.Course">
<id column="c_id" property="c_id"/>
<result column="c_name" property="c_name"/>
</collection>
</resultMap>
<select id="selectTeacherAndCourse" resultMap="teacherResultMap" >
select t.t_id,t.t_name,c.c_id from teacher t
left join course c on t.t_id = c.t_id
where t.t_id = #{id}
</select>
动态sql
动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。
使用动态 SQL 并非一件易事,但借助可用于任何 SQL 映射语句中的强大的动态 SQL 语言,MyBatis 显著地提升了这一特性的易用性。
如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
if
<select id="findActiveBlogWithTitleLike"
resultType="Blog">
SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
</select>
choose、when、otherwise
<select id="findActiveBlogLike"
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>
trim、where、set
<select id="findActiveBlogLike"
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 author_name like #{author.name}
</if>
</where>
</select>
加上这个标签前面有where子句前面有and或or会被删除
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
set标签子句的末尾删掉逗号
<trim prefix="SET" suffixOverrides=",">
...
</trim>
foreach
<select id="selectStudentList" resultMap="getStudentRm" parameterType="list">
select * from student
<where>
and s_id in
<foreach collection="list" item="item" open="(" close=")" separator=",">
#{item}
</foreach>
</where>
</select>