Mybatis全部标签与解释说明

在这里插入图片描述

一、定义SQL语句

(1)select 标签的使用
   属性介绍:
     id :唯一的标识符.
     parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User或user
     resultType :语句返回值类型或别名。注意,如果是集合,那么这里填写的
     是集合的泛型,而不是集合本身(resultType 与resultMap 不能并用)
   例子:

<select id="userList" parameterType="user" resultType="User">
 select * from user where name =#{name}
</select>

(2)insert 标签的使用
    属性介绍:
      id :唯一的标识符
      parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User

(3)delete 标签的使用
    例:

<delete id="deleteUser" parameterType="int"> 
 delete from user 
 where id = #{id} 
</delete>

(4)update 标签的使用
    类似于insert

二、配置对象属性与查询结果集

(1)resultMap 标签的使用

基本作用:建立SQL查询结果字段与实体属性的映射关系信息

查询的结果集转换为java对象,方便进一步操作

将结果集中的列与java对象中的属性对应起来并将值填充进去

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

例:

<resultMap id="getStudentRM" type="EStudnet">
	<id property="id" column="ID"/>
	<result property="studentName" column="Name"/>
	<result property="studentAge" column="Age"/>
	</resultMap>
	<select id="getStudent" resultMap="getStudentRM">
		SELECT ID, Name, Age
		FROM TStudent
	</select>
</resultMap>

标签说明:
主标签
id:该resultMap的标志
type:返回值的类名,此例中返回EStudnet类
子标签:

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

三、动态拼接SQL

(1)if 标签的使用

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

例:

<select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">     
    SELECT * from STUDENT_TBL ST       
WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
</select> 

但是此时如果studentName是null或空字符串,此语句很可能报错或查询结果为空。此时我们使用if动态sql语句先进行判断,如果值为null或等于空字符串,我们就不进行此条件的判断。

修改为:

<select id=" getStudentListLikeName " parameterType="StudentEntity" resultMap="studentResultMap">     
    SELECT * from STUDENT_TBL ST      
    <if test="studentName!=null and studentName!='' ">     
        WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
    </if>     
</select>   

(2)foreach 标签的使用

foreach标签主要用于构建in条件,他可以在sql中对集合进行迭代。如下:

  <delete id="deleteBatch"> 
    delete from user where id in
    <foreach collection="array" item="id" index="index" open="(" close=")" separator=",">
      #{id}
    </foreach>
  </delete>

我们假如说参数为---- int[] ids = {1,2,3,4,5} ----那么打印之后的SQL如下:

  delete form user where id in (1,2,3,4,5)

释义:

collection :collection属性的值有三个分别是list、array、map三种,分别对应的参数类型为:List、数组、map集合,我在上面传的参数为数组,所以值为array

item : 表示在迭代过程中每一个元素的别名

index :表示在迭代过程中每次迭代到的位置(下标)

open :前缀

close :后缀

separator :分隔符,表示迭代时每个元素之间以什么分隔

我们通常可以将之用到批量删除、添加等操作中。

(3)choose 标签的使用

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

例如下面例子,同样把所有可以限制的条件都写上,方面使用。选择条件顺序,when标签的从上到下的书写顺序:

<select id="getStudentListChooseEntity" parameterType="StudentEntity" resultMap="studentResultMap">     
    SELECT * from STUDENT_TBL ST      
    <where>     
        <choose>     
            <when test="studentName!=null and studentName!='' ">     
                    ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
            </when>     
            <when test="studentSex!= null and studentSex!= '' ">     
                    AND ST.STUDENT_SEX = #{studentSex}      
            </when>     
            <when test="studentBirthday!=null">     
                AND ST.STUDENT_BIRTHDAY = #{studentBirthday}      
            </when>     
            <when test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">     
                AND ST.CLASS_ID = #{classEntity.classID}      
            </when>     
            <otherwise>     
                      
            </otherwise>     
        </choose>     
    </where>     
</select>     

四、格式化输出

(1)where
当if标签较多时,这样的组合可能会导致错误。例如,like姓名,等于指定性别等:

Xml代码

[html] view plain copy
<!-- 查询学生list,like姓名,=性别 -->     
<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">     
    SELECT * from STUDENT_TBL ST      
        WHERE      
        <if test="studentName!=null and studentName!='' ">     
            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
        </if>     
        <if test="studentSex!= null and studentSex!= '' ">     
            AND ST.STUDENT_SEX = #{studentSex}      
        </if>     
</select>     

如果上面例子,参数studentName为null或’’,则或导致此sql组合成“WHERE AND”之类的关键字多余的错误SQL。
这时我们可以使用where动态语句来解决。这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。
上面例子修改为:
Xml代码

[html] view plain copy
<!-- 查询学生list,like姓名,=性别 -->     
<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">     
    SELECT * from STUDENT_TBL ST      
    <where>     
        <if test="studentName!=null and studentName!='' ">     
            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
        </if>     
        <if test="studentSex!= null and studentSex!= '' ">     
            AND ST.STUDENT_SEX = #{studentSex}      
        </if>     
    </where>     
</select>     

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

Xml代码

[html] view plain copy
<!-- 更新学生信息 -->     
<update id="updateStudent" parameterType="StudentEntity">     
    UPDATE STUDENT_TBL      
       SET STUDENT_TBL.STUDENT_NAME = #{studentName},      
           STUDENT_TBL.STUDENT_SEX = #{studentSex},      
           STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},      
           STUDENT_TBL.CLASS_ID = #{classEntity.classID}      
     WHERE STUDENT_TBL.STUDENT_ID = #{studentID};      
</update>     

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

Xml代码

[html] view plain copy
<!-- 更新学生信息 -->     
<update id="updateStudent" parameterType="StudentEntity">     
    UPDATE STUDENT_TBL      
    <set>     
        <if test="studentName!=null and studentName!='' ">     
            STUDENT_TBL.STUDENT_NAME = #{studentName},      
        </if>     
        <if test="studentSex!=null and studentSex!='' ">     
            STUDENT_TBL.STUDENT_SEX = #{studentSex},      
        </if>     
        <if test="studentBirthday!=null ">     
            STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},      
        </if>     
        <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' ">     
            STUDENT_TBL.CLASS_ID = #{classEntity.classID}      
        </if>     
    </set>     
    WHERE STUDENT_TBL.STUDENT_ID = #{studentID};      
</update>     

(3)trim
trim是更灵活的去处多余关键字的标签,他可以实践where和set的效果。
where例子的等效trim语句:

[html] view plain copy
<!-- 查询学生list,like姓名,=性别 -->     
<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">     
    SELECT * from STUDENT_TBL ST      
    <trim prefix="WHERE" prefixOverrides="AND|OR">     
        <if test="studentName!=null and studentName!='' ">     
            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
        </if>     
        <if test="studentSex!= null and studentSex!= '' ">     
            AND ST.STUDENT_SEX = #{studentSex}      
        </if>     
    </trim>     
</select>     

set例子的等效trim语句:
Xml代码

[html] view plain copy
<!-- 更新学生信息 -->     
<update id="updateStudent" parameterType="StudentEntity">     
    UPDATE STUDENT_TBL      
    <trim prefix="SET" suffixOverrides=",">     
        <if test="studentName!=null and studentName!='' ">     
            STUDENT_TBL.STUDENT_NAME = #{studentName},      
        </if>     
        <if test="studentSex!=null and studentSex!='' ">     
            STUDENT_TBL.STUDENT_SEX = #{studentSex},      
        </if>     
        <if test="studentBirthday!=null ">     
            STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},      
        </if>     
        <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' ">     
            STUDENT_TBL.CLASS_ID = #{classEntity.classID}      
        </if>     
    </trim>     
    WHERE STUDENT_TBL.STUDENT_ID = #{studentID};      
</update>     

五、配置关联关系

(1)association

一对一

association通常用来映射一对一的关系,例如,有个类user,对应的实体类如下:(getter,setter方法省略)

private String id;//主键
private String userName;//用户姓名

有个类Article,对应的实体类如下:

private String id;//主键
private String articleTitle;//文章标题
private String articleContent;//文章内容

如果我想查询一个用户的时候,也查到他写的一篇文章,可以怎样写呢?在类user加入一个属性article

private String id;//主键
private String userName;//用户姓名
private Article article;//新增的文章属性

2、mapper.xml 我在user类的mapper.xml这样配置

<resultMap id="userResultMap" type="test.mybatis.entity.User">
<id column="id" property="id" jdbcType="VARCHAR" javaType="java.lang.String"/>
<result column="userName" property="userName" jdbcType="VARCHAR" javaType="java.lang.String"/>
//这里把user的id传过去
<association property="article" column="id" 
select="test.mybatis.dao.articleMapper.selectArticleByUserId" />//test.mybatis.dao.articleMapper为命名空间
</resultMap>

同时,我的article对应的xml这样写:

<resultMap id="articleResultMap" type="test.mybatis.entity.Article">
<id column="id" property="id" jdbcType="VARCHAR" javaType="java.lang.String"/>
<result column="articleTitle" property="articleTitle" jdbcType="VARCHAR" javaType="java.lang.String"/>
<result column="articleContent" property="articleContent" jdbcType="VARCHAR" javaType="java.lang.String"/>
</resultMap>

(当然,这里还有查询user表的语句,省略)

同时,在article对应的xml有这样的select语句:

<select id="selectArticleByUserId"
	parameterType="java.lang.String"
	resultMap="ArticleResultMap">
	select * from tb_article where userId=#{userId} </select>

(2)collection

一对多

实体类增加对应属性

private String id;//主键
private String userName;//用户姓名
private List

articleList;
userMapper.xml这样配置

<resultMap id="userResultMap" type="test.mybatis.entity.User">
	<id column="id" property="id" jdbcType="VARCHAR" javaType="java.lang.String"/>
	<result column="userName" property="userName" jdbcType="VARCHAR" 		
	javaType="java.lang.String"/>
	//这里把user的id传过去
	<collection property="articleList" column="id" 
	select="test.mybatis.dao.articleMapper.selectArticleListByUserId" />
</resultMap>

或者配合 ofType 一起使用

<resultMap id="userResultMap" type="test.mybatis.entity.User">
	<id column="id" property="id" jdbcType="VARCHAR" javaType="java.lang.String"/>
	<result column="userName" property="userName" jdbcType="VARCHAR" 		
	javaType="java.lang.String"/>
	//这里把user的id传过去
	<collection property="articleList" ofType="test.mybatis.entity.Article"> 
		<id column="id" property="id" jdbcType="VARCHAR" javaType="java.lang.String"/>
	<result column="articleTitle" property="articleTitle" jdbcType="VARCHAR" 		
	javaType="java.lang.String"/>
	<result column="articleContent" property="articleContent" jdbcType="VARCHAR" 		
	javaType="java.lang.String"/>
	</collection>
</resultMap>

以下省略,类同,Mybatis会把结果封装成List类型。

如果我还想通过Article表另一张表,比如文章中有个fk_id,也可以像上面这样重复配置,把fk_id当做与另一张表关联的参数,那时就可以通过用户查到文章,查到文章关联的另一张表了。

六、mybatis可以使用useGeneratedKeys来自动生成id(其他数字的值也一样可以):

    <insert id="save" parameterType="UserAlias" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO userinfo(username,age)
        VALUES
        (#{username}, #{age})
        </insert>

keyProperty这里指定自动增长的字段,我这里是id。所以下边的insert中可以不写id字段,前提是数据库中一定要设置好id的自增长。

如果数据库中没有设置自增长可以用下面代码:

    <insert id="save" parameterType="UserAlias" useGeneratedKeys="true" keyProperty="id">
        <selectKey keyProperty="id" resultType="long" order="BEFORE">
          SELECT if(max(id) is null,1,MAX(id) + 1 ) as id from userinfo
        </selectKey>
        INSERT INTO userinfo(id,username,age)
        VALUES
        (#{id}, #{username}, #{age})
        </insert>

七、SQL标签

更多用于写sql语句的一部分,写在配置文件中的常量

八、include标签

用于引用常量

九、在方法参数的前面写上@Param(“参数名”),表示给参数命名,名称就是括号中的内容

List<CuxTodoItems> selectItembyparam1(@Param("id") int userId,@Param("pty") String Priority);

给入参 int userId 命名为id,然后sql语句…where userId= #{id} 中就可以根据 id 得到参数值了。
xml映射对应示例

  <select id="selectItembyparam1" resultMap="BaseResultMap">
      SELECT *
      FROM  cux_todo_items
      WHERE user_id = #{id}
      AND   priority = #{pty}
  </select>

十、mybatis replace into用法

<insert id="updateEmployeeSalaryById">
      REPLACE INTO empsalary (eid,sid) VALUES(#{eid},#{sid})
  </insert>

replace into 跟 insert 功能类似,不同点在于:replace into 首先尝试插入数据到表中:

  1. 如果发现表中已经有此行数据(根据主键或者唯一索引判断)则先删除此行数据,然后插入新的数据。
  2. 否则,直接插入新数据。

要注意的是:插入数据的表必须有主键或者是唯一索引!否则的话,replace into 会直接插入数据,这将导致表中出现重复的数据。

十一、Mybatis中什么时候应该声明jdbcType
疑问来自于,有时候Mapper.xml中

pid = #{pid,jdbcType=INTEGER}

pid = #{pid}

都可以用

那么问题来了,

Mybatis中什么时候应该声明jdbcType?

当Mybatis不能自动识别你传入对象的类型时。

什么情况下,Mybatis不能自动识别我的传入类型?

例如:当你传入空值的时候。

简而言之,加上肯定不会报错。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis中的`<resultMap>`元素用于将查询结果映射到Java对象中。它有以下子标签: 1. `<id>`:用于映射主键字段,可以设置`column`属性指定数据库中的列名,`property`属性指定Java对象中的属性名,`jdbcType`属性指定JDBC类型,`typeHandler`属性指定类型处理器等。 举例: ```xml <resultMap id="userMap" type="com.example.User"> <id column="id" jdbcType="BIGINT" property="id"/> <!--其他字段映射--> </resultMap> ``` 2. `<result>`:用于映射普通字段,与`<id>`类似,可以设置`column`、`property`、`jdbcType`和`typeHandler`等属性。 举例: ```xml <resultMap id="userMap" type="com.example.User"> <id column="id" jdbcType="BIGINT" property="id"/> <result column="name" jdbcType="VARCHAR" property="name"/> <!--其他字段映射--> </resultMap> ``` 3. `<association>`:用于映射关联对象,可以设置`property`属性指定Java对象中的属性名,`javaType`属性指定关联对象的类型,`columnPrefix`属性指定关联对象在数据库中的列名前缀,`select`属性指定关联对象的查询语句等。 举例: ```xml <resultMap id="orderMap" type="com.example.Order"> <id column="id" jdbcType="BIGINT" property="id"/> <result column="name" jdbcType="VARCHAR" property="name"/> <association property="user" javaType="com.example.User" columnPrefix="user_"> <id column="user_id" jdbcType="BIGINT" property="id"/> <result column="user_name" jdbcType="VARCHAR" property="name"/> </association> </resultMap> ``` 4. `<collection>`:用于映射关联对象集合,可以设置`property`属性指定Java对象中的属性名,`ofType`属性指定集合中元素的类型,`columnPrefix`属性指定集合元素在数据库中的列名前缀,`select`属性指定集合元素的查询语句等。 举例: ```xml <resultMap id="userMap" type="com.example.User"> <id column="id" jdbcType="BIGINT" property="id"/> <result column="name" jdbcType="VARCHAR" property="name"/> <collection property="orders" ofType="com.example.Order" columnPrefix="order_"> <id column="order_id" jdbcType="BIGINT" property="id"/> <result column="order_name" jdbcType="VARCHAR" property="name"/> </collection> </resultMap> ``` 以上就是`<resultMap>`元素的子标签及其用途的简单介绍和示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值