当前位置: 首页 > news >正文

MyBatis总结(2)- MyBatis实现原理(三)

核心配置

  • JavaBeanMapper.xml(sql映射)

作用

JavaBeanMapper.xml实现:

  1. 用来干什么?

    • 定义Sql语句映射。相对照JDBC的实现,是将原本的Sql代码提取出来,最终根据映射关系执行Sql操作。
  2. 好处?

    • 解耦,mapper只关心定义Sql的映射关系,与java代码分离,更易维护。
  3. 如何使用?

    • 先来展示一个基本的mapper xml,这里涉及到主要的几个标签元素:
      • Select
      • Insert
      • Update
      • Delete
      • ResultMap
      • Sql
      • Cache
<?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="org.example.daos.UserMapper"><resultMap id="userMap" type="Customer"><result column="pwd" property="password"/></resultMap><select id="getUserList" resultMap="userMap">SELECT * FROM mybatis.user</select><select id="getUserListByRowBounds" resultMap="userMap">SELECT * FROM mybatis.user</select><!-- 模糊查询1--><!--<select id="getUserListForFuzzyQuery" resultType="org.example.pojo.User">SELECT * FROM mybatis.user where name like #{name}</select>--><!-- 模糊查询2: "%"--><select id="getUserListForFuzzyQuery" resultType="org.example.pojo.User">SELECT * FROM mybatis.user where name like "%"#{name}</select><!-- 形参只有一个,且为基本类型时,parameterType可省略(parameterType="int" )--><select id="getUserById" resultType="org.example.pojo.User">SELECT * FROM mybatis.user where id = #{id}</select><insert id="addUser" parameterType="org.example.pojo.User">INSERT INTO mybatis.user(id, name, pwd) values (#{id},#{name},#{pwd})</insert><update id="updateUserByUser" parameterType="org.example.pojo.User">UPDATE mybatis.user set name=#{name}, pwd=#{pwd} where id=#{id}</update><update id="updateUserByMap" parameterType="map">UPDATE mybatis.user set name=#{userName}, pwd=#{userPwd} where id=#{userId}</update><delete id="deleteUser" parameterType="int">DELETE FROM mybatis.user where id=#{id}</delete>
</mapper>
  1. 具体的标签元素:
    • Select:
      • 这里的重点是,resultType,resultMap的使用,两者只能二选一
        • ResultType:语句中返回结果的类全限定名或别名。一般是该sql映射方法的返回值类型。特殊的,如果是集合类型,则只需定义集合的泛型类型即可。
        • ResultMap:对外部 resultMap 的命名引用。一般用于处理复杂的映射结果查询,比如:多表查询(一对多,多对一):

多对一查询:

<?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="org.example.daos.StudentMapper"><!-- 多对一查询方式1:Teacher再查一次:子查询相当于:select id, name, tid from student where tid = (select id from teacher where id = tid)--><!--<resultMap id="StudentTeacher1" type="Student"><id property="id" column="id"/><result column="name" property="name"/><association property="teacher" column="tid" select="getTeacherById" javaType="Teacher"/></resultMap><select id="getStudentList" resultMap="StudentTeacher1">select * from student</select><select id="getTeacherById" resultType="Teacher">select * from teacher where id=#{tid}</select>--><!-- 多对一查询方式2:按照结果嵌套, 联表查询相当于:select s.id sid, s.name sname, t.id tid, t.name tname from student s, teacher t where s.tid = t.id--><select id="getStudentList" resultMap="StudentTeacher2">select s.id sid, s.name sname, t.id tid, t.name tname from student s, teacher t where s.tid = t.id</select><resultMap id="StudentTeacher2" type="Student"><result property="id" column="sid"/><result property="name" column="sname"/><association property="teacher" javaType="Teacher"><id column="id" property="tid"/><result property="name" column="tname"/></association></resultMap></mapper>

一对多查询:

<?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="org.example.daos.TeacherMapper"><!--一对多:方式1:联表查询 --><select id="getTeacherById" resultMap="TeacherStudent">select t.id tid, t.name tname, s.id sid, s.name sname from teacher t, student s where t.id = s.tid and t.id=#{tid}</select><resultMap id="TeacherStudent" type="Teacher"><result property="id" column="tid"/><result property="name" column="tname"/><collection property="studentList" ofType="Student"><result property="id" column="sid"/><result property="name" column="sname"/><result property="tid" column="tid"/></collection></resultMap><!--一对多:方式2:子查询 --><select id="getTeacherById2" resultMap="TeacherStudent2">select * from teacher where id=#{tid}</select><resultMap id="TeacherStudent2" type="Teacher"><result column="id" property="id"/><collection property="studentList" column="id" ofType="Student" select="getStudentByTid"/></resultMap><select id="getStudentByTid" resultType="Student">select * from student where tid=#{tid}</select>
</mapper>
  • Insert:涉及到自动生成主键id的设置(keyProperty, useGeneratedKeys),多行插入(foreach)
  • Update:
  • Delete:
<!-- 自动生成主键id -->
<insert id="insertAuthor" useGeneratedKeys="true"keyProperty="id">insert into Author (username,password,email,bio)values (#{username},#{password},#{email},#{bio})
</insert><!-- 多行插入 -->
<insert id="insertAuthor" useGeneratedKeys="true"keyProperty="id">insert into Author (username, password, email, bio) values<foreach item="item" collection="list" separator=",">(#{item.username}, #{item.password}, #{item.email}, #{item.bio})</foreach>
</insert><update id="updateAuthor">update Author setusername = #{username},password = #{password},email = #{email},bio = #{bio}where id = #{id}
</update><delete id="deleteAuthor">delete from Author where id = #{id}
</delete>
  • Sql:sql语句重用片段。也可动态赋值
<sql id="if_title_author"><if test="title!= null">AND title = #{title}</if><if test="author != null">AND author = #{author}</if>
</sql><select id="queryBlog1" parameterType="map">select * from blog where 1=1<include refid="if_title_author"/>
</select><!-- 动态赋值: ${include_target}, property -->
<sql id="someinclude">from<include refid="${include_target}"/>
</sql>
<select id="select" resultType="map">selectfield1, field2, field3<include refid="someinclude"><property name="prefix" value="Some"/></include>
</select>
  • 参数的定义:
    • 如果一个列允许使用 null 值,并且会使用值为 null 的参数,就必须要指定 JDBC 类型(jdbcType)
#{average,javaType=double,jdbcType=NUMERIC,typeHandler=MyTypeHandler,numericScale=2}
  • 字符串替换: ${}方式不会被预编译转义,可以通过这种方式指定某个字符串column,而非对应的数值。但存在sql注入风险。
@Select("select * from user where ${column} = #{value}")
User findByColumn(@Param("column") String column, @Param("value") String value);
  • association & collection :collection 用于一对多,association用于多对一。
association 联表查询
<association property="author" column="blog_author_id" javaType="Author"><id property="id" column="author_id"/><result property="username" column="author_username"/>
</association>association 子表查询
<resultMap id="blogResult" type="Blog"><association property="author" column="author_id" javaType="Author" select="selectAuthor"/>
</resultMap>collection子表查询
<collection property="posts" column="id" ofType="Post" select="selectPostsForBlog"/>collection联表查询
<resultMap id="blogResult" type="Blog"><id property="id" column="blog_id" /><result property="title" column="blog_title"/><collection property="posts" ofType="Post"><id property="id" column="post_id"/><result property="subject" column="post_subject"/><result property="body" column="post_body"/></collection>
</resultMap>
  • OfType:
<collection property="posts" javaType="ArrayList" column="id" ofType="Post" select="selectPostsForBlog"/>

可以读作: “posts 是一个存储 Post 的 ArrayList 集合” 。且在一般情况下,MyBatis 可以推断 javaType 属性,因此并不需要填写。

  • 缓存Cache:

    • 一级缓存:默认开启。SqlSession级别的缓存,也叫本地缓存
    • 二级缓存:基于namespace级别的缓存,针对mapper <cache>, LRU, FIFO,开启二级缓存,需要在对于mapper上,加入标签元素<Cache>即可
    • 当会话sqlSession提交commit或关闭close时,一级缓存的数据才会提交到二级缓存中!!!
    • 缓存顺序:当查询业务来到DAO层时:
      • 先查看二级缓存;
      • 再查看一级缓存;
      • 最后再查数据库
  • 动态Sql:解决在定义Sql映射时,拼接sql语句:where子句条件,SET子句,多条语句foreach的编写。参考链接

    • If, choose, foreach, trim
  • 分页:limit

    • Select * from user limit startIndex, pageSize
    • RowBounds(selectList (String statement, Object parameter, RowBounds rowBounds)
    • Mybatis PageHelper
  • 注解开发: 参考链接

相关文章:

  • 支付宝H5支付
  • wsl子系统ubuntu20.04 设置docker服务开机自启动
  • 第4天:用户认证系统实现
  • 【大分享06】收、治、用、安“四管齐下”, 做好多业务系统电子文件归档与管理
  • Spire.PDF for .NET【文档操作】演示:如何删除 PDF 中的图层
  • Matlab基础篇:数据输入输出
  • NXP i.MX8系列平台开发讲解 - 3.15 Linux 之USB子系统(一)
  • 【机器学习300问】119、什么是语言模型?
  • 人工智能在气象预报领域的崛起:GraphCast引领新纪元
  • 使用 Redis + Lua 实现分布式限流
  • 如何修改jupyter notebook 默认把文件夹
  • 会声会影2024永久破解和谐版下载 包含激活码序列号
  • 深入理解RunLoop
  • 决策树算法详细介绍原理和实现
  • HarmonyOS角落里的知识—Stage模型应用程序
  • Angular4 模板式表单用法以及验证
  • AzureCon上微软宣布了哪些容器相关的重磅消息
  • conda常用的命令
  • ES6系统学习----从Apollo Client看解构赋值
  • gf框架之分页模块(五) - 自定义分页
  • Git同步原始仓库到Fork仓库中
  • golang 发送GET和POST示例
  • JS字符串转数字方法总结
  • PAT A1092
  • Ruby 2.x 源代码分析:扩展 概述
  • SAP云平台运行环境Cloud Foundry和Neo的区别
  • Spring技术内幕笔记(2):Spring MVC 与 Web
  • 服务器之间,相同帐号,实现免密钥登录
  • 开源中国专访:Chameleon原理首发,其它跨多端统一框架都是假的?
  • 老板让我十分钟上手nx-admin
  • 前端
  • 使用Gradle第一次构建Java程序
  • 微信公众号开发小记——5.python微信红包
  • 文本多行溢出显示...之最后一行不到行尾的解决
  • SAP CRM里Lead通过工作流自动创建Opportunity的原理讲解 ...
  • 国内唯一,阿里云入选全球区块链云服务报告,领先AWS、Google ...
  • 好程序员大数据教程Hadoop全分布安装(非HA)
  • 如何在招聘中考核.NET架构师
  • ​​​​​​​Installing ROS on the Raspberry Pi
  • ### RabbitMQ五种工作模式:
  • #QT(一种朴素的计算器实现方法)
  • #微信小程序:微信小程序常见的配置传旨
  • (6)【Python/机器学习/深度学习】Machine-Learning模型与算法应用—使用Adaboost建模及工作环境下的数据分析整理
  • (ibm)Java 语言的 XPath API
  • (LNMP) How To Install Linux, nginx, MySQL, PHP
  • (板子)A* astar算法,AcWing第k短路+八数码 带注释
  • (六)Hibernate的二级缓存
  • (十)【Jmeter】线程(Threads(Users))之jp@gc - Stepping Thread Group (deprecated)
  • (十七)Flask之大型项目目录结构示例【二扣蓝图】
  • (原創) 未来三学期想要修的课 (日記)
  • (转)Google的Objective-C编码规范
  • * CIL library *(* CIL module *) : error LNK2005: _DllMain@12 already defined in mfcs120u.lib(dllmodu
  • .equals()到底是什么意思?
  • .helper勒索病毒的最新威胁:如何恢复您的数据?
  • .md即markdown文件的基本常用编写语法