一.mybatis-config.xml文件

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <!-- 根标签 -->
  6. <configuration>
  7. <!--读取外部资源,通过方法参数传递的属性具有最高优先级,resource/url 属性中指定的配置文件次之,最低优先级的是 properties 属性中指定的属性。-->
  8. <properties resource="org/mybatis/example/config.properties">
  9. <property name="username" value="dev_user"/>
  10. <property name="password" value="F2Fa3!33TYyg"/>
  11. </properties>
  12.  
  13. <!--settings设置-->
  14. <settings>
  15. <!--全局性地开启或关闭所有映射器配置文件中已配置的任何缓存-->
  16. <setting name="cacheEnabled" value="true"/>
  17. <!--延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。-->
  18. <setting name="lazyLoadingEnabled" value="true"/>
  19. <setting name="multipleResultSetsEnabled" value="true"/>
  20. <setting name="useColumnLabel" value="true"/>
  21. <setting name="useGeneratedKeys" value="false"/>
  22. <setting name="autoMappingBehavior" value="PARTIAL"/>
  23. <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
  24. <setting name="defaultExecutorType" value="SIMPLE"/>
  25. <setting name="defaultStatementTimeout" value="25"/>
  26. <setting name="defaultFetchSize" value="100"/>
  27. <setting name="safeRowBoundsEnabled" value="false"/>
  28. <!--是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn-->
  29. <setting name="mapUnderscoreToCamelCase" value="false"/>
  30. <setting name="localCacheScope" value="SESSION"/>
  31. <setting name="jdbcTypeForNull" value="OTHER"/>
  32. <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
  33. </settings>
  34.  
  35. <!--类型别名-->
  36. <typeAliases>
  37. <!--type:实体类的全路径。alias:别名,通常首字母大写-->
  38. <!--<typeAlias type="com.zpc.mybatis.pojo.User" alias="User"/>-->
  39. <!--扫描包-->
  40. <package name="com.zpc.mybatis.pojo"/>
  41. </typeAliases>
  42.  
  43. <!--插件(plugins)-->
  44. <plugins>
  45. <plugin interceptor="org.mybatis.example.ExamplePlugin">
  46. <property name="someProperty" value="100"/>
  47. </plugin>
  48. </plugins>
  49.  
  50. <!-- 环境,可以配置多个,default:指定采用哪个环境 -->
  51. <environments default="development">
  52. <environment id="development">
  53. <transactionManager type="JDBC">
  54. <property name="..." value="..."/>
  55. </transactionManager>
  56. <dataSource type="POOLED">
  57. <property name="driver" value="${driver}"/>
  58. <property name="url" value="${url}"/>
  59. <property name="username" value="${username}"/>
  60. <property name="password" value="${password}"/>
  61. </dataSource>
  62. </environment>
  63. </environments>
  64.  
  65. <!-- 使用相对于类路径的资源引用 -->
  66. <mappers>
  67. <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  68. <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
  69. <mapper resource="org/mybatis/builder/PostMapper.xml"/>
  70. </mappers>
  71.  
  72. </configuration>

二.Mapper XML文件详解

1.CRUD标签

select

select中的几个属性说明:
id属性:当前名称空间下的statement的唯一标识。必须。要求id和mapper接口中的方法的名字一致。
resultType:将结果集映射为java的对象类型。必须(和 resultMap 二选一)
parameterType:传入参数类型。可以省略

  1. <select
  2. id="selectPerson"       //当前名称空间下的statement的唯一标识
  3. parameterType="int"      //将会传入这条语句的参数的类全限定名或别名(可以省略)
  4. parameterMap="deprecated"  //该参数已废弃
  5. resultType="hashmap"     //期望从这条语句中返回结果的类全限定名或别名
  6. resultMap="personResultMap" //对外部 resultMap 的命名引用
  7. flushCache="false"      //将其设置为 true 后,只要语句被调用,都会导致本地缓存和二级缓存被清空
  8. useCache="true"        //将其设置为 true 后,将会导致本条语句的结果被二级缓存缓存起来
  9. timeout="10"          //这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数
  10. fetchSize="256"        //这是一个给驱动的建议值,尝试让驱动程序每次批量返回的结果行数等于这个设置值
  11. statementType="PREPARED"   //可选 STATEMENTPREPAREDCALLABLE
  12. resultSetType="FORWARD_ONLY">
  1. <select id="selectPerson" parameterType="int" resultType="User">
  2. SELECT * FROM PERSON WHERE ID = #{id}
  3. </select>

insert, update 和 delete

insert 的几个属性说明:
id:唯一标识,随便写,在同一个命名空间下保持唯一,使用动态代理之后要求和方法名保持一致
parameterType:参数的类型,使用动态代理之后和方法的参数类型一致
useGeneratedKeys:开启主键回写
keyColumn:指定数据库的主键
keyProperty:主键对应的pojo属性名
标签内部:具体的sql语句。

  1. <insert
  2. id="insertAuthor"
  3. parameterType="domain.blog.Author"  //将会传入这条语句的参数的类全限定名或别名
  4. flushCache="true"            //将其设置为 true 后,只要语句被调用,都会导致本地缓存和二级缓存被清空
  5. statementType="PREPARED"        //可选 STATEMENTPREPAREDCALLABLE
  6. keyProperty=""              //(仅适用于 insertupdate)指定能够唯一识别对象的属性
  7. keyColumn=""               //(仅适用于 insertupdate)设置生成键值在表中的列名
  8. useGeneratedKeys=""           //(仅适用于 insertupdate)这会令 MyBatis 使用 JDBCgetGeneratedKeys 方法来取出由数据库内部生成的主键(比如:像 MySQLSQL Server 这样的关系型数据库管理系统的自动递增字段)
  9. timeout="20">
  1. <insert id="insertAuthor">
  2. insert into Author (id,username,password,email,bio)
  3. values (#{id},#{username},#{password},#{email},#{bio})
  4. </insert>

update的几个属性说明:

id属性:当前名称空间下的statement的唯一标识(必须属性);
parameterType:传入的参数类型,可以省略。
标签内部:具体的sql语句。

  1. <update
  2. id="updateAuthor"
  3. parameterType="domain.blog.Author"
  4. flushCache="true"
  5. statementType="PREPARED"
  6. timeout="20">
  1. <update id="updateAuthor">
  2. update Author set
  3. username = #{username},
  4. password = #{password},
  5. email = #{email},
  6. bio = #{bio}
  7. where id = #{id}
  8. </update>

delete 的几个属性说明:
id属性:当前名称空间下的statement的唯一标识(必须属性);
parameterType:传入的参数类型,可以省略。
标签内部:具体的sql语句。

  1. <delete
  2. id="deleteAuthor"
  3. parameterType="domain.blog.Author"
  4. flushCache="true"
  5. statementType="PREPARED"
  6. timeout="20">
  1. <delete id="deleteAuthor">
  2. delete from Author where id = #{id}
  3. </delete>

2.#{}和${}

通常在方法的参数列表上加上一个注释@Param(“xxxx”) 显式指定参数的名字,然后通过${“xxxx”}或#{“xxxx”}
sql语句动态生成的时候,使用${};
sql语句中某个参数进行占位的时候#{}

  1. /**
  2. * #号
  3. * @param username1
  4. * @return
  5. */
  6. User queryUserListByName1(@Param("username1") String username1);
  7.  
  8. /**
  9. * $号
  10. * @param username2
  11. * @return
  12. */
  13. User queryUserListByName2(@Param("username2") String username2);
  14.  
  15. <select id="queryUserListByName1" resultType="com.zpc.mybatis.pojo.User">
  16. select * from tb_user WHERE user_name=#{username1}
  17. </select>
  18.  
  19. <select id="queryUserListByName2" resultType="com.zpc.mybatis.pojo.User">
  20. select * from tb_user WHERE user_name='${username2}'//手动加了引号
  21. </select>

3.resultMap

使用:

4.sql片段

例如在UserMapper.xml中定义如下片段:

  1. <sql id="commonSql">
  2. id,
  3. user_name,
  4. password,
  5. name,
  6. age,
  7. sex,
  8. birthday,
  9. created,
  10. updated
  11. </sql>

则可以在UserMapper.xml中使用它:

  1. <select id="queryUserById" resultMap="userResultMap">
  2. select <include refid="commonSql"></include> from tb_user where id = #{id}
  3. </select>
  4.  
  5. <select id="queryUsersLikeUserName" resultType="User">
  6. select <include refid="commonSql"></include> from tb_user where user_name like "%"#{userName}"%"
  7. </select>

5.动态sql

if

使用动态 SQL 最常见情景是根据条件包含 where 子句的一部分。比如:

  1. <select id="findActiveBlogWithTitleLike"
  2. resultType="Blog">
  3. SELECT * FROM BLOG
  4. WHERE state = ‘ACTIVE’
  5. <if test="title != null">
  6. AND title like #{title}
  7. </if>
  8. </select>

choose、when、otherwise

它有点像 Java 中的 switch 语句

  1. <select id="findActiveBlogLike"
  2. resultType="Blog">
  3. SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  4. <choose>
  5. <when test="title != null">
  6. AND title like #{title}
  7. </when>
  8. <when test="author != null and author.name != null">
  9. AND author_name like #{author.name}
  10. </when>
  11. <otherwise>
  12. AND featured = 1
  13. </otherwise>
  14. </choose>
  15. </select>

trim、where、set

  1. <select id="findActiveBlogLike"
  2. resultType="Blog">
  3. SELECT * FROM BLOG
  4. <where>
  5. <if test="state != null">
  6. state = #{state}
  7. </if>
  8. <if test="title != null">
  9. AND title like #{title}
  10. </if>
  11. <if test="author != null and author.name != null">
  12. AND author_name like #{author.name}
  13. </if>
  14. </where>
  15. </select>

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:

  1. <trim prefix="WHERE" prefixOverrides="AND |OR ">
  2. ...
  3. </trim>

用于动态更新语句的类似解决方案叫做 setset 元素可以用于动态包含需要更新的列,忽略其它不更新的列。比如:

  1. <update id="updateAuthorIfNecessary">
  2. update Author
  3. <set>
  4. <if test="username != null">username=#{username},</if>
  5. <if test="password != null">password=#{password},</if>
  6. <if test="email != null">email=#{email},</if>
  7. <if test="bio != null">bio=#{bio}</if>
  8. </set>
  9. where id=#{id}
  10. </update>

这个例子中,set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

来看看与 set 元素等价的自定义 trim 元素吧:

  1. <trim prefix="SET" suffixOverrides=",">
  2. ...
  3. </trim>

foreach

动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。比如:

  1. <select id="selectPostIn" resultType="domain.blog.Post">
  2. SELECT *
  3. FROM POST P
  4. WHERE ID in
  5. <foreach item="item" index="index" collection="list"
  6. open="(" separator="," close=")">
  7. #{item}
  8. </foreach>
  9. </select>

6.高级查询

一对一查询(人和订单)

  1. public class Order {
  2. private Integer id;
  3. private Long userId;
  4. private String orderNumber;
  5. private Date created;
  6. private Date updated;
  7. private User user;
  8. }
  1. <resultMap id="OrderUserResultMap" type="com.zpc.mybatis.pojo.Order" autoMapping="true">
  2. <id column="id" property="id"/>
  3. <!--association:完成子对象的映射-->
  4. <!--property:子对象在父对象中的属性名-->
  5. <!--javaType:子对象的java类型-->
  6. <!--autoMapping:完成子对象的自动映射,若开启驼峰,则按驼峰匹配-->
  7. <association property="user" javaType="com.zpc.mybatis.pojo.User" autoMapping="true">
  8. <id column="user_id" property="id"/>
  9. </association>
  10. </resultMap>
  11.  
  12. <select id="queryOrderWithUserByOrderNumber" resultMap="OrderUserResultMap">
  13. select * from tb_order o left join tb_user u on o.user_id=u.id where o.order_number = #{number}
  14. </select>

一对多查询(订单和订单详情)

  1. public class Order {
  2. private Integer id;
  3. private Long userId;
  4. private String orderNumber;
  5. private Date created;
  6. private Date updated;
  7. private User user;
  8. private List<OrderDetail> detailList;
  9. }
  1. <resultMap id="OrderUserDetailResultMap" type="com.zpc.mybatis.pojo.Order" autoMapping="true">
  2. <id column="id" property="id"/>
  3. <!--collection:定义子对象集合映射-->
  4. <!--association:完成子对象的映射-->
  5. <!--property:子对象在父对象中的属性名-->
  6. <!--javaType:子对象的java类型-->
  7. <!--autoMapping:完成子对象的自动映射,若开启驼峰,则按驼峰匹配-->
  8. <association property="user" javaType="com.zpc.mybatis.pojo.User" autoMapping="true">
  9. <id column="user_id" property="id"/>
  10. </association>
  11. <collection property="detailList" javaType="List" ofType="com.zpc.mybatis.pojo.OrderDetail" autoMapping="true">
  12. <id column="id" property="id"/>
  13. </collection>
  14. </resultMap>
  15.  
  16. <select id="queryOrderWithUserAndDetailByOrderNumber" resultMap="OrderUserDetailResultMap">
  17. select * from tb_order o
  18. left join tb_user u on o.user_id=u.id
  19. left join tb_orderdetail od on o.id=od.order_id
  20. where o.order_number = #{number}
  21. </select>

多对多查询(订单和商品)

  1. <resultMap id="OrderUserDetailItemResultMap" type="com.zpc.mybatis.pojo.Order" autoMapping="true">
  2. <id column="id" property="id"/>
  3. <association property="user" javaType="com.zpc.mybatis.pojo.User" autoMapping="true">
  4. <id column="user_id" property="id"/>
  5. </association>
  6. <collection property="detailList" javaType="List" ofType="com.zpc.mybatis.pojo.OrderDetail" autoMapping="true">
  7. <id column="detail_id" property="id"/>
  8. <association property="item" javaType="com.zpc.mybatis.pojo.Item" autoMapping="true">
  9. <id column="item_id" property="id"/>
  10. </association>
  11. </collection>
  12. </resultMap>
  13.  
  14. <select id="queryOrderWithUserAndDetailItemByOrderNumber" resultMap="OrderUserDetailItemResultMap">
  15. select * ,od.id as detail_id from tb_order o
  16. left join tb_user u on o.user_id=u.id
  17. left join tb_orderdetail od on o.id=od.order_id
  18. left join tb_item i on od.item_id=i.id
  19. where o.order_number = #{number}
  20. </select>

mybatis入门详解的更多相关文章

  1. Linq之旅:Linq入门详解(Linq to Objects)

    示例代码下载:Linq之旅:Linq入门详解(Linq to Objects) 本博文详细介绍 .NET 3.5 中引入的重要功能:Language Integrated Query(LINQ,语言集 ...

  2. SQL注入攻防入门详解

    =============安全性篇目录============== 本文转载 毕业开始从事winfrm到今年转到 web ,在码农届已经足足混了快接近3年了,但是对安全方面的知识依旧薄弱,事实上是没机 ...

  3. SQL注入攻防入门详解(2)

    SQL注入攻防入门详解 =============安全性篇目录============== 毕业开始从事winfrm到今年转到 web ,在码农届已经足足混了快接近3年了,但是对安全方面的知识依旧薄弱 ...

  4. Quartz 入门详解

    Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,它可以与J2EE与J2SE应用程序相结合也可以单独使用.Quartz可以用来创建简单或为运行十个,百个, ...

  5. Redis快速入门详解

    Redis入门详解 Redis简介 Redis安装 Redis配置 Redis数据类型 Redis功能 持久化 主从复制 事务支持 发布订阅 管道 虚拟内存 Redis性能 Redis部署 Redis ...

  6. [转]SQL注入攻防入门详解

    原文地址:http://www.cnblogs.com/heyuquan/archive/2012/10/31/2748577.html =============安全性篇目录============ ...

  7. [置顶] xamarin android toolbar(踩坑完全入门详解)

    网上关于toolbar的教程有很多,很多新手,在使用toolbar的时候踩坑实在太多了,不好好总结一下,实在浪费.如果你想学习toolbar,你肯定会去去搜索androd toolbar,既然你能看到 ...

  8. 转:JAVAWEB开发之权限管理(二)——shiro入门详解以及使用方法、shiro认证与shiro授权

    原文地址:JAVAWEB开发之权限管理(二)——shiro入门详解以及使用方法.shiro认证与shiro授权 以下是部分内容,具体见原文. shiro介绍 什么是shiro shiro是Apache ...

  9. webpack入门详解

    webpack入门详解(基于webpack 3.5.4  2017-8-22) webpack常用命令: webpack --display-error-details    //执行打包 webpa ...

随机推荐

  1. Leetcode 981. Time Based Key-Value Store(二分查找)

    题目来源:https://leetcode.com/problems/time-based-key-value-store/description/ 标记难度:Medium 提交次数:1/1 代码效率 ...

  2. java design pattern - adapter pattern

    场景 适配器模式 总结 参考资料 场景 在编程中我们经常会遇到驴头不对马嘴的情况,比如以前是继承A的接口的对象,现在外部调用的时候需要该对象已B接口的形式来调用 ,这个时候我们可以让对象同时集成A和B ...

  3. spring入门-整合junit和web

    整合Junit 导入jar包 基本 :4+1 测试:spring-test-5.1.3.RELEASE.jar 让Junit通知spring加载配置文件 让spring容器自动进行注入 1234567 ...

  4. Job for network.service failed because the control process exited with error code问题

    Job for network.service failed because the control process exited with error code问题 因为是克隆的,所以需要重新修改静 ...

  5. brup安装证书抓取https

    brup安装证书抓取https 0x00下载 下载安装brup 前提是需要java环境 0X01配置brup 配置brup的代理设置 0X02设置浏览器 我使用的是火狐,以下都以火狐为例 0X03证书 ...

  6. Java入门教程十(抽象类接口内部类匿名类)

    抽象类(abstract) 一个类只定义了一个为所有子类共享的一般形式,至于细节则交给每一个子类去实现,这种类没有任何具体的实例,只具有一些抽象的概念,那么这样的类称为抽象类. 在面向对象领域,抽象类 ...

  7. Node REPL环境

    1.概述 REPL全称Read,Eval,Print,Loop,简单理解为接收用户输入,执行用户输入,打印执行结果并输出到控制台,进行下一次轮回,可以进行一些简单的测试,类似于浏览器的控制台. 命令行 ...

  8. Go-数据类型以及变量,常量,函数,包的使用

    Go-数据类型以及变量,常量,函数,包的使用 一.数据类型 1.字符串类型 string -双引号包裹的:"xxx" -反引号包裹,可以换行, 注意: 区别于python,是没有单 ...

  9. Rust入坑指南:朝生暮死

    今天想和大家一起把我们之前挖的坑再刨深一些.在Java中,一个对象能存活多久全靠JVM来决定,程序员并不需要去关心对象的生命周期,但是在Rust中就大不相同,一个对象从生到死我们都需要掌握的很清楚. ...

  10. SpringBoot入门系列(二)如何返回统一的数据格式

    前面介绍了Spring Boot的优点,然后介绍了如何快速创建Spring Boot 项目.不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/zhangweizhong/ ...