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

ゝ一世哀愁。 2022-04-13 14:15 460阅读 0赞

前言

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

正文

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

常用的顶级元素

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

ResultMap

一个具体的代码如下

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

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

sql

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

  1. <sql id="Base_Column_List" >
  2. id, name, password
  3. </sql>

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

select

一个简单的select函数

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

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

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

    select id, name,password from user where id=’id’

insert

类似,实例代码

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

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

delete

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

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

update

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

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

发表评论

表情:
评论列表 (有 0 条评论,460人围观)

还没有评论,来说两句吧...

相关阅读

    相关 MybatisXML映射文件

    MyBatis 针对 SQL 构建,真正强大在于它的映射语句。 SQL 映射文件有很少的几个顶级元素(按照它们应该被定义的顺序): cache – 给定命名空间的缓存配