Mybatis标签的基本用法总结(Mysql)

一、增删查改
①查询

<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="Object">
            java执行的方法名           返回的数据集合                传入的参数类型
    select * from student where id=#{id}
</select>

②插入

<insert id="insert" parameterType="Object">
       java执行的方法名    传入的参数类型
        insert into student    
    <trim    prefix="("    suffix=")"    suffixOverrides="," > 
             前缀添加(      后缀添加)          删除最后一个逗号
        <if test="name != null  ">  NAME,  </if>   
            判断name是否为null,   为true的话
    </trim>    
    <trim    prefix="values("    suffix=")"    suffixOverrides="," >
        <if test="name != null  ">  #{name},  </if>    
    </trim>
</insert>

③修改

<update id="updateByPrimaryKeySelective" parameterType="com.adc.da.product.entity.User" >
                java执行的方法名                        传入的参数类型
  update user
  <set >
    <if test="uname != null" >
      uname = #{uname},
    </if>
    <if test="sex != null" >
      sex = #{sex},
    </if>
  </set>
  where id = #{id}
</update>

④删除

<delete id="deleteByPrimaryKey" parameterType="Object">
            java执行的方法名         传入的参数类型
        delete      from student where id=#{id}
</delete>

二、resultMap
resultMap是Mybatis最强大的元素,它可以将查询到的复杂数据(比如查询到几个表中数据)映射到一个结果集当中。
使用resultType进行输出映射,只有查询出来的列名和pojo(实体bean)中的属性名一致,该列才可以映射成功。
简单来说也就是你的数据库字段和JavaBean里的字段名称必须一致才能映射成功。
所以当我们JavaBean中的字段名和数据库字段名称有不同的时候,或者是多表查询的时候,一般会使用resultMap

属性描述
property需要映射到JavaBean 的属性名称。
column数据表的列名或者标签别名。
javaType一个完整的类名,或者是一个类型别名。如果你匹配的是一个JavaBean,那MyBatis 通常会自行检测到。然后,如果你是要映射到一个HashMap,那你需要指定javaType 要达到的目的。
jdbcType数据表支持的类型列表。这个属性只在insert,update 或delete 的时候针对允许空的列有用。JDBC 需要这项,但MyBatis 不需要。如果你是直接针对JDBC 编码,且有允许空的列,而你要指定这项。
typeHandler使用这个属性可以覆写类型处理器。这项值可以是一个完整的类名,也可以是一个类型别名。
<resultMap id="唯一的标识" type="pojo路径">
    <id column="数据库主键" property="pojo对应属性" jdbcType="数据库字段类型"  javaType="pojo属性的类型"/>
    <result column="表的一个字段(可以为任意表的一个字段)" property="pojo中的属性" jdbcType="字段类型" javaType="pojo属性的类型"/>


    <association property="外键" javaType="外键表pojo的路径" >
        <id column="数据库外键表主键" property="关联pojo对象的主键属性" jdbcType="字段类型" />
        <result  column="外键表的字段" property="关联pojo对象的属性" jdbcType="字段类型" />
    </association>


    <association property="role" javaType="com.queen.mybatis.bean.Role">
        <id column="role_id" property="id"/>
        <result column="roleName" property="roleName"/>
    </association>


    <association property="role" select="com.queen.mybatis.mapper.RoleMapper.getRoleById" column="roleId">
    															getRoleById方法select * from t_user 
    </association>


    <collection property="menus" ofType="cn.com.hellowood.springsecurity.model.MenuModel"   javaType="java.util.ArrayList">
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="value" property="value" jdbcType="VARCHAR"/>
    </collection>


    <collection property="外键的pojo属性" column="外键对应主键pojo属性,作为参数传入被调用的 Select 语句" ofType="外键表pojo路径" javaType="外键类型" select="getRoloById">
        <id column="集合中pojo对象对应的表的主键字段" jdbcType="字段类型" property="集合中pojo对象的主键属性" />
        <result column="可以为任意表的字段" jdbcType="字段类型" property="集合中的pojo对象的属性" />  
    </collection>
</resultMap>

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

<if test="name != null and name != ''">
         and NAME = #{name}
</if>

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

<select id="getStudentListChoose" parameterType="Student" resultMap="BaseResultMap">
SELECT * from STUDENT WHERE 1=1
    <where>
        <choose>
            <when test="Name!=null and student!='' ">
                AND name LIKE CONCAT(CONCAT('%', #{student}),'%')
            </when>
            <when test="hobby!= null and hobby!= '' ">
                AND hobby = #{hobby}
            </when>
            <otherwise>
                AND AGE = 15
            </otherwise>
        </choose>
    </where>
</select>

③where
where标记的作用类似于动态sql中的set标记,他的作用主要是用来简化sql语句中where条件判断的书写的,如下所示:

<select id="selectByParams" parameterType="map" resultType="user">
  select * from user
  <where>
    <if test="id != null ">id=#{id}</if>
    <if test="name != null and name.length()>0" >and name=#{name}</if>
    <if test="gender != null and gender.length()>0">and gender = #{gender}</if>
  </where>
</select>     

在上述SQL中加入ID的值为null的话,那么打印出来的SQL为:select * from user where /and/ name=“xx” and gender=“xx”
在上面加粗的地方是没有and的,where 标记会自动将其后第一个条件的and或者是or给忽略掉

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

  • prefix:最前面添加的值
  • suffix:最后面添加的值
  • prefixOverrides:删除的第一个
  • suffixOverrides:删除的最后一个
select * from user
  <trim prefix="WHERE" prefixoverride="AND |OR">
    <if test="name != null and name.length()>0"> AND name=#{name}</if>
    <if test="gender != null and gender.length()>0"> AND gender=#{gender}</if>
  </trim>

假如说name和gender的值都不为null的话打印的SQL为:select * from user where /and/ name = ‘xx’ and gender = ‘xx’
在加粗的地方是不存在第一个and的,上面两个属性的意思如下:
  prefix:前缀      
  prefixoverride:去掉第一个and或者是or

update user
  <trim prefix="set" suffixoverride="," suffix=" where id = #{id} ">
    <if test="name != null and name.length()>0"> name=#{name} , </if>
    <if test="gender != null and gender.length()>0"> gender=#{gender} ,  </if>
  </trim>

假如说name和gender的值都不为null的话打印的SQL为:update user set name=‘xx’ , gender=‘xx’ /,/ where id=‘x’
在加粗的地方不存在逗号,而且自动加了一个set前缀和where后缀,上面三个属性的意义如下,其中prefix意义如上:
  suffix:后缀
  suffixoverride:去掉最后一个逗号(也可以是其他的标记,就像是上面前缀中的and一样)

⑤set
set标记是mybatis提供的一个智能标记,我一般将其用在修改的sql中,例如以下情况:

<update>
  update user
  <set>
    <if test="name != null and name.length()>0">name = #{name},</if>
    <if test="gender != null and gender.length()>0">gender = #{gender},</if>
  </set>
  where id = #{id}
</update>

在上述的代码片段当中,假如说现在三个字段都有值得话,那么上面打印的SQL语句如下:
update user set name=‘xxx’ , gender=‘xx’ /,/ where id=‘x’
在上面加粗的地方是没有逗号的,也就是说set标记已经自动帮助我们把最后一个逗号给去掉了

⑥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 :分隔符,表示迭代时每个元素之间以什么分隔
我们通常可以将之用到批量删除、添加等操作中。

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

<!-- 查询字段 -->
    <sql id="Base_Column_List">
        ID,MAJOR,BIRTHDAY,AGE,NAME,HOBBY
    </sql>

<!-- 查询条件 -->
    <sql id="Example_Where_Clause">
        where 1=1
        <trim suffixOverrides=",">
            <if test="id != null and id !=''">
                and id = #{id}
            </if>
            <if test="major != null and major != ''">
                and MAJOR = #{major}
            </if>
        </trim>
    </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>

五、其他
like模糊查询字符串拼接

<if test="uname != null" >
  <bind name="_uname" value="'%' + uname + '%'" />
  and uname like #{_uname}
</if>
<if test="sex != null" >
  and sex like concat(concat('%',#{sex}),'%')
</if>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值