mybatis的常用动态sql标签

一. 定义 sql 语句

select 标签

属性介绍:

  • id :唯一的标识符.
  • parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User 或 user
  • resultType :语句返回值类型或别名。注意,如果是集合,那么这里填写的是集合的泛型,而不是集合本身(resultType 与 resultMap 不能并用)
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="Object">
    select * from student where id=#{id}
</select>

insert 标签

属性介绍:

  • id :唯一的标识符
  • parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User

delete 标签

属性同 insert

update 标签

属性同 insert

二. 配置 JAVA 对象属性与查询结果集中列名对应关系

resultMap 标签的使用
基本作用:

  • 建立 SQL 查询结果字段与实体属性的映射关系信息
  • 查询的结果集转换为 java 对象,方便进一步操作。
  • 将结果集中的列与 java 对象中的属性对应起来并将值填充进去

!注意:与 java 对象对应的列不是数据库中表的列名,而是查询后结果集的列名

<resultMap id="BaseResultMap" type="com.online.charge.platform.student.model.Student">
    <id property="id" column="id" />
    <result column="NAME" property="name" />
    <result column="HOBBY" property="hobby" />
    <result column="MAJOR" property="major" />
    <result column="BIRTHDAY" property="birthday" />
    <result column="AGE" property="age" />
</resultMap>

<!--查询时resultMap引用该resultMap -->
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="Object">
    select id,name,hobby,major,birthday,age from student where id=#{id}
</select>

标签说明:

主标签:

  • id:该 resultMap 的标志
  • type:返回值的类名,此例中返回 Studnet 类

子标签:

  • id:用于设置主键字段与领域模型属性的映射关系,此处主键为 ID,对应 id。
  • result:用于设置普通字段与领域模型属性的映射关系

三. 动态 sql 拼接

if 标签

if 标签通常用于 WHERE 语句、UPDATE 语句、INSERT 语句中,通过判断参数值来决定是否使用某个查询条件、判断是否更新某一个字段、判断是否插入某个字段的值。

foreach 标签

foreach 标签主要用于构建 in 条件,可在 sql 中对集合进行迭代。也常用到批量删除、添加等操作中。

属性介绍:

  • collection:collection 属性的值有三个分别是 list、array、map 三种,分别对应的参数类型为:List、数组、map 集合。
  • item :表示在迭代过程中每一个元素的别名
  • index :表示在迭代过程中每次迭代到的位置(下标)
  • open :前缀
  • close :后缀
  • separator :分隔符,表示迭代时每个元素之间以什么分隔

choose 标签

有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。MyBatis 提供了 choose 元素,按顺序判断 when 中的条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when
的条件都不满则时,则执行 otherwise 中的 sql。类似于 Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。

if 是与(and)的关系,而 choose 是或(or)的关系。

四. 格式化输出

where 标签

当 if 标签较多时,这样的组合可能会导致错误。 如下:

当 name 值为 null 时,查询语句会出现 “WHERE AND” 的情况,解决该情况除了将"WHERE"改为“WHERE 1=1”之外,还可以利用 where
标签。这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以 AND 或 OR 开头的,则它会剔除掉。

set 标签

没有使用 if 标签时,如果有一个参数为 null,都会导致错误。当在 update 语句中使用 if 标签时,如果最后的 if 没有执行,则或导致逗号多余错误。使用 set 标签可以将动态的配置 set
关键字,和剔除追加到条件末尾的任何不相关的逗号。

使用 set+if 标签修改后,如果某项为 null 则不进行更新,而是保持数据库原值。

trim 标签

trim标记是一个格式化的标记,主要用于拼接sql的条件语句(前缀或后缀的添加或忽略),可以完成set或者是where标记的功能。

trim属性主要有以下四个

  • prefix:在trim标签内sql语句加上前缀
  • suffix:在trim标签内sql语句加上后缀
  • prefixOverrides:指定去除多余的前缀内容,如:prefixOverrides=“AND | OR”,去除trim标签内sql语句多余的前缀"and"或者"or"。
  • suffixOverrides:指定去除多余的后缀内容。

例如在update中

如果name和hobby的值都不为空的话,会执行如下语句

会忽略最后一个“,” ;

在select中

如果name和hobby的值都不为空的话,会执行如下语句

会为片段添加 “WHERE” 前缀,并忽略第一个 “and” ;

当然,避免出现“WHERE AND”还有其他方法,如下

<!--将where提取出来,并加上“1=1”的查询条件 -->
select * from student where 1=1
	<trim suffixOverrides=",">
		<if test="name != null and name != ''">
			and NAME = #{name}
		</if>
		<if test="hobby != null and hobby != ''">
			and HOBBY = #{hobby}
		</if>
	</trim>

用在insert中

<insert id="insert" parameterType="Object">
    insert into student 
	<trim prefix="(" suffix=")" suffixOverrides=",">
		<if test="name != null">
			NAME,
		</if>
		<if test="hobby != null  ">
			HOBBY,
		</if>
	</trim>
	<trim prefix="values(" suffix=")" suffixOverrides=",">
		<if test="name != null  ">
			#{name},
		</if>
		<if test="hobby != null  ">
			#{hobby},
		</if>
	</trim>
</insert>

可以为生成格式正确的insert语句。

五. 配置关联关系

最近一直把collection和association弄混,所以为了增强自己的记忆,就撸一个关系出来算是总结罢了


1. 关联-association
2. 集合-collection

比如同时有User.java和Card.java两个类

User.java如下:

public class User{

private Card card_one;

private List<Card> card_many;

}

在映射card_one属性时用association标签, 映射card_many时用collection标签.

所以association是用于一对一和多对一,而collection是用于一对多的关系

下面就用一些例子解释下吧

association-一对一

人和身份证的关系

下面是pojo

1

2

3

4

5

public class Card implements Serializable {

private Integer id ;

private String code ;

//省略set和get方法.

}

 

1

2

3

4

5

6

7

8

9

public class Person implements Serializable {

private Integer id ;

private String name ;

private String sex ;

private Integer age ;

//人和身份证是一对一的关系

private Card card ;

//省略set/get方法.

}

下面是mapper和实现的接口

1

2

3

4

5

6

7

package com . glj . mapper ;

 

import com . glj . poji . Card ;

 

public interface CardMapper {

Card selectCardById ( Integer id ) ;

}

 

1

2

3

4

5

6

7

8

9

<? xml version = "1.0" encoding = "UTF-8" ?>

< ! DOCTYPE mapper

     PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

     "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

< mapper namespace = "com.glj.mapper.CardMapper" >

< select id = "selectCardById" parameterType = "int" resultType = "com.glj.poji.Card" >

select * from tb_card where id = #{id}

< / select >

< / mapper >

 

1

2

3

4

5

6

7

package com . glj . mapper ;

 

import com . glj . poji . Person ;

 

public interface PersonMapper {

Person selectPersonById ( Integer id ) ;

}

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<? xml version = "1.0" encoding = "UTF-8" ?>

< ! DOCTYPE mapper

     PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

     "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

< mapper namespace = "com.glj.mapper.PersonMapper" >

< resultMap type = "com.glj.poji.Person" id = "personMapper" >

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

< result property = "name" column = "name" / >

< result property = "sex" column = "sex" / >

< result property = "age" column = "age" / >

< association property = "card" column = "card_id"

select = "com.glj.mapper.CardMapper.selectCardById"

javaType = "com.glj.poji.Card" >

< / association >

< / resultMap >

< select id = "selectPersonById" parameterType = "int" resultMap = "personMapper" >

select * from tb_person where id = #{id}

< / select >

< / mapper >

PersonMapper.xml 还使用association的分步查询。

同理多对一,也是一样

只要那个pojo出现private Card card_one;

即使用association


collection 一对多和association的多对一关系

学生和班级的一对多的例子

pojo类

1

2

3

4

5

6

7

8

9

10

11

12

13

package com . glj . pojo ;

 

import java . io . Serializable ;

import java . util . List ;

 

public class Clazz implements Serializable {

private Integer id ;

private String code ;

private String name ;

         //班级与学生是一对多的关系

private List < Student > students ;

//省略set/get方法

}

 

1

2

3

4

5

6

7

8

9

10

11

12

13

package com . glj . pojo ;

 

import java . io . Serializable ;

 

public class Student implements Serializable {

private Integer id ;

private String name ;

private String sex ;

private Integer age ;

         //学生与班级是多对一的关系

private Clazz clazz ;

//省略set/get方法

}

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<? xml version = "1.0" encoding = "UTF-8" ?>

< ! DOCTYPE mapper

     PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

     "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

< mapper namespace = "com.glj.mapper.ClazzMapper" >

< select id = "selectClazzById" parameterType = "int" resultMap = "clazzResultMap" >

select * from tb_clazz where id = #{id}

< / select >

< resultMap type = "com.glj.pojo.Clazz" id = "clazzResultMap" >

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

< result property = "code" column = "code" / >

< result property = "name" column = "name" / >

< ! -- property : 指的是集合属性的值 , ofType:指的是集合中元素的类型 -- >

< collection property = "students" ofType = "com.glj.pojo.Student"

column = "id" javaType = "ArrayList"

fetchType = "lazy" select = "com.glj.mapper.StudentMapper.selectStudentByClazzId" >

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

< result property = "name" column = "name" / >

< result property = "sex" column = "sex" / >

< result property = "age" column = "age" / >

< / collection >

< / resultMap >

< / mapper >

 

1

2

3

4

5

6

7

package com . glj . mapper ;

 

import com . glj . pojo . Clazz ;

 

public interface ClazzMapper {

Clazz selectClazzById ( Integer id ) ;

}

ClazzMapper使用到了集合-collection 即为一对多,一个班级面对多个学生

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<? xml version = "1.0" encoding = "UTF-8" ?>

< ! DOCTYPE mapper

     PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

     "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

< mapper namespace = "com.glj.mapper.StudentMapper" >

< select id = "selectStudentById" parameterType = "int" resultMap = "studentResultMap" >

select * from tb _clazz c , tb _student s where c . id = s . id and s . id = #{id}

< / select >

< select id = "selectStudentByClazzId" parameterType = "int" resultMap = "studentResultMap" >

select * from tb_student where clazz_id = #{id}

< / select >

< resultMap type = "com.glj.pojo.Student" id = "studentResultMap" >

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

< result property = "name" column = "name" / >

< result property = "sex" column = "sex" / >

< result property = "age" column = "age" / >

< association property = "clazz" javaType = "com.glj.pojo.Clazz" >

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

< result property = "code" column = "code" / >

< result property = "name" column = "name" / >

< / association >

< / resultMap >

< / mapper >

 

1

2

3

4

5

6

7

package com . glj . mapper ;

 

import com . glj . pojo . Student ;

 

public interface StudentMapper {

Student selectStudentById ( Integer id ) ;

}

StudentMapper则是与班级为多对一关系,所以使用了关联-association


嗯,希望我以后又不记得二者的关系时,能感谢现在总结的自己

 

附上一张mybatis的类型别名图

六. 定义常量及引用

sql 标签

当多种类型的查询语句的查询字段或者查询条件相同时,可以将其定义为常量,方便调用。为求 <select> 结构清晰也可将 sql 语句分解。

include 标签

用于引用定义的常量

<!-- 查询所有,不分页 -->
<select id="selectAll" resultMap="BaseResultMap">
    SELECT
    <include refid="Base_Column_List" />
    FROM student
    <include refid="Example_Where_Clause" />
</select>


<!-- 分页查询 -->
<select id="select" resultMap="BaseResultMap">
    select * from (
        select tt.*,rownum as rowno from
        (
            SELECT
            <include refid="Base_Column_List" />
            FROM student
            <include refid="Example_Where_Clause" />
            ) tt
            <where>
                <if test="pageNum != null and rows != null">
                    and rownum
                    <![CDATA[<=]]>#{page}*#{rows}
                </if>
            </where>
        ) table_alias
    where table_alias.rowno>#{pageNum}
</select>


<!-- 根据条件删除 -->
<delete id="deleteByEntity" parameterType="java.util.Map">
    DELETE FROM student
    <include refid="Example_Where_Clause" />
</delete>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值