mybatis的XML映射文件中的函数-mybatis(1)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/babybabyup/article/details/84638864

前言

由mybatis的逆向代码生成器生成的6个基本函数在日常开发中是有些力不从心的,我们可以写写自定义函数,去完成一些复杂的操作。

正文

继续以之前建立的springboot项目为基础,来学习mybatis的xml映射文件的写法,主要写一下我用到比较多的一些元素。具体可以看官网
项目建立文章配置springboot和mybatis逆向生成器

常用的顶级元素

  • ResultMap 定义了数据库的列和实体属性的映射关系
  • sql 定义要重复应用的代码
  • select查询函数
  • delete删除函数
  • insert插入函数
  • update更新函数

ResultMap

一个具体的代码如下

<resultMap id="BaseResultMap" type="com.nick.hello.entity.User" >
    <id column="id" property="id" jdbcType="VARCHAR" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
  </resultMap>

其含义是:java中的com.nick.hello.entity.User的属性id,name,password分别自动映射到数据库中的列名 id,name,password.这个在我们数据库列名与实体属性不是完全对应时很有用。

sql

sql中定义的代码可以重复使用

  <sql id="Base_Column_List" >
    id, name, password
  </sql>

指定数据库中的所有列名。要引用时只需要添加refid="id"

select

一个简单的select函数

<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select 
    <include refid="Base_Column_List" />
    from user
    where id = #{id,jdbcType=VARCHAR}
  </select>

这个函数的作用是通过id来查找记录。

  • id不能省略,可以被用来代表这个语句,对应Mapper中的函数名
  • ResultMap定义结果怎么映射
  • parameterType是传入参数类型
  • #{}就相当于jdbc中的?
select id, name,password from user where id='id'

insert

类似,实例代码

<insert id="insert" parameterType="com.nick.hello.entity.User" >
    insert into user (id, name, password
      )
    values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
      )
  </insert>

参数类型是我们自己定义的User

delete

  <delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
    delete from user
    where id = #{id,jdbcType=VARCHAR}
  </delete>

删除语句,通过id删除记录

update

  <update id="updateByPrimaryKey" parameterType="com.nick.hello.entity.User" >
    update user
    set name = #{name,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR}
    where id = #{id,jdbcType=VARCHAR}
  </update>

这些是简单的xml映射函数,mybatis还支持更加强大的动态sql语句。xml映射函数简洁但是功能强大,也许几行映射函数在业务逻辑中要实现的话就需要几倍的代码量了。

猜你喜欢

转载自blog.csdn.net/babybabyup/article/details/84638864