mybatis3中文文档_MyBatis3 学习记录

这篇博客主要涵盖了MyBatis3的官方中文文档,包括MyBatis Generator的下载,MapperXML的使用,以及各种动态SQL元素如等。此外,还详细讲解了resultMap的高级映射功能,如association和collection的一对一、一对多联合查询,并介绍了discriminator的使用,用于根据特定列的值进行不同的映射处理。
摘要由CSDN通过智能技术生成

69303be802b7fd9c2aed60f633c11d77.png

图片来自于Unity3D官网

MyBatis3官方中文文档

mybatis-GitHub下载

MyBatis Generator文档

MyBatis Generator-GitHub下载

MyBatis pagehelpe文档

mapperXML

<?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="cn.xxx.xxx">

</mapper>

内置别名

别名java类型_bytebyte_longlong_shortshort_intint_integerint_doubledouble_floatfloat_booleanbooleanstringStringbyteBytelongLongshortShortintIntegerintegerIntegerdoubleDoublefloatFloatbooleanBooleandateDatedecimalBigDecimalbigdecimalBigDecimalobjectObjectmapMaphashmapHashMaplistListarraylistArrayListcollectionCollectioniteratorIterator

基本用法

insert @insert("")

1.返回主键的第一种形式
useGeneratedKeys=true 返回自增主键
keyProperty:映射的主键ID
<insert id="insert" parameterType="bean" useGeneratedKeys="true" keyProperty="keyID"> </insert>
 
 2.返回主键的第二种形式
 order:执行顺序
        AFTER 表示 SELECT LAST_INSERT_ID() 在insert执行之后执行,用于自增主键
        BEFORE 表示 SELECT LAST_INSERT_ID() 在insert执行之前执行,这样的话就拿不到主键了,适合主键不是自增的类型
keyProperty:映射的主键ID
<insert id="insert" parameterType="bean">
    <selectKey resultType="java.lang.Long" order="AFTER" keyProperty="keyID">
          SELECT LAST_INSERT_ID()
    </selectKey>
    inser ....
</insert>

<insert id="insert" parameterType="bean" databaseId="oracle">
    <selectKey resultType="java.lang.Long" order="BEFORE" keyProperty="keyID">
          select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1
    </selectKey>
    inser ....  #{keyID}
</insert>

update @update("")

<update id="insert" parameterType="bean"></update>

select @select("")

<select id="select" resultType="resultbean" parameterType="parameterbean" ></select>
 
 <select id="select" resultMap="resultMap" parameterType="parameterbean" ></select>

返回Map

<!--
	    @MapKey("id")
	    public Map<Integer, Employee> getEmpByLastNameLikeReturnMap(String lastName); 
	 -->
 	<select id="getEmpByLastNameLikeReturnMap" resultType="com.xxx.Employee">
 		select * from tbl_employee where last_name like #{lastName}
 	</select>
 
    <!--key为列名,值为数据-->
 	<!--public Map<String, Object> getEmpByIdReturnMap(Integer id);  -->
 	<select id="getEmpByIdReturnMap" resultType="map">
 		select * from tbl_employee where id=#{id}
 	</select>

动态SQL

<if>

<if test="state != null and state != ''"> </if>

<choose>, <when>, <otherwise>

作用类似于
switch (key) {
    case value:
    	break;
    default:
    	break;
}

  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>

<where>

生成where,去掉前面无用的and
 
 <where> </where>

<set>

生成set,去掉后面无用的逗号
 
 <set> </set>

<trim>

prefix: 前缀
suffix:后缀
prefixOverrides:覆盖前缀
suffixOverrides:覆盖后缀

<trim prefix="WHERE" prefixOverrides="AND|OR"><trim>

<trim prefix="SET" suffixOverrides=","><trim>

<trim prefix="(" suffix=")" suffixOverrides="," ><trim>

<foreach>

collection:集合名称(如果没有用@param起名默认为list)
item:遍历的当前的个元素
index:当前的索引
open:拼接开始字符
separator:每个元素的分隔符
close:拼接结束字符

<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
    #{item}
</foreach>

<bind>

<bind name="_name" value="'%'+ name +'%'"></bind>

调用:where name like #{_name}

<sql>

sql片段,抽取公用sql
    <sql id="column">
        name,sex
    </sql>
    
    使用:
    select 
        <include> refid="column"></include>
    from
        user
        
    高级方式见文档=》》http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#sql

内置参数

1. _parameter

    代表整个传递进来的参数
    单个:即为当前参数
    多个:为参数封装map的key

 <if test="_parameter !=null"> </if>
2. _databaseId

    数据库别名,用于区分不同数据库下执行不同sql

 <if test="_databaseId == 'mysql'"> </if>

resultMap 高级映射

<resultMap id="" type="bean" autoMapping="true">
        <constructor>
            <idArg/>
            <arg/>
        </constructor>
        <id property="id" column="id" />
        <result property="userName" column="user_name" />
        <association property=""/>
        <collection property=""/>
        <discriminator javaType="">
            <case value=""></case>
        </discriminator>
    </resultMap>
constructor - 用于在实例化类时,注入结果到构造方法中 ​ idArg - ID 参数;标记出作为 ID 的结果可以帮助提高整体性能 ​ arg - 将被注入到构造方法的一个普通结果 ​ name - 构造方法形参的名字. 3.4.3支持 id – 一个 ID 结果;标记出作为 ID 的结果可以帮助提高整体性能 result – 注入到字段或 JavaBean 属性的普通结果 association – 一个复杂类型的关联;许多结果将包装成这种类型 嵌套结果映射 – 关联可以指定为一个 resultMap 元素,或者引用一个 collection – 一个复杂类型的集合 嵌套结果映射 – 集合可以指定为一个 resultMap 元素,或者引用一个 discriminator – 使用结果值来决定使用哪个 resultMap case – 基于某些值的结果映射 嵌套结果映射 – 一个 case 也是一个映射它本身的结果,因此可以包含很多相 同的元素,或者它可以参照一个外部的 resultMap。

举例用法

1 resultMap基本使用

@Alias("emp")
public class Employee {
	private Integer id;
	private String lastName;
	private String email;
	private String gender;
	
	...
	
}
<!--
	    type:自定义规则的Java类型
	    id:唯一id方便引用
	 -->
	<resultMap type="emp" id="empMap">
    	<!--指定主键列的封装规则
	    	id定义主键会底层有优化;
	    	column:指定哪一列
		    property:指定对应的javaBean属性
		-->
		<id column="id" property="id"/>
		<result column="last_name" property="lastName"/>
		<result column="email" property="email"/>
		<result column="gender" property="gender"/>
	</resultMap>
	或
	<resultMap type="emp" id="empMap">
    	<!--指定主键列的封装规则
	    	id定义主键会底层有优化;
	    	column:指定哪一列
		    property:指定对应的javaBean属性
		-->
    	<constructor>
           <idArg column="id" name="id" />
           <arg column="last_name" name="lastName" />
           <arg column="email" name="email" />
        </constructor>
	</resultMap>
	
	<!-- public Employee getEmpById(Integer id); -->
	<select id="getEmpById"  resultMap="empMap">
		select * from tbl_employee where id=#{id}
	</select>

2.1 association 联合映射

public class Employee {
	private Integer id;
	private String lastName;
	private String email;
	private String gender;
	
	private Department dept;
}
<resultMap type="com.xxx.Employee" id="empAndDeotMap">
		<id column="id" property="id"/>
		<result column="last_name" property="lastName"/>
		<result column="gender" property="gender"/>
		
		<!--1.级联属性-->
		<id column="did" property="dept.id"/>
		<result column="dept_name" property="dept.deptName"/>
		或
		<!--2.association可以指定联合的javaBean对象
    		property="dept":指定哪个属性是联合的对象
    		javaType:指定这个属性对象的类型[不能省略]
		-->
		<association property="dept" javaType="com.xxx.Department">
			<id column="did" property="id"/>
			<result column="dept_name" property="departmentName"/>
		</association>
		
	</resultMap>
	<!--  public Employee getEmpAndDept(Integer id);-->
	<select id="getEmpAndDept" resultMap="empAndDeotMap">
		SELECT e.id id,e.last_name last_name,e.gender gender,e.d_id d_id,
		d.id did,d.dept_name dept_name FROM tbl_employee e,tbl_dept d
		WHERE e.d_id=d.id AND e.id=#{id}
	</select>

2.2 association 分布联合映射

- 好处:1.使用现有方法
       2.懒加载(使用则去查询,在结果集中get了分布查询中的属性,才会去查询)
        需要全局开启懒加载
    mybatis:
      configuration:
        # 开启懒加载,默认为true
        lazy-loading-enabled: true
        # 设置属性按需加载,默认为true(true为全部加载,false为按需加载)
        aggressive-lazy-loading: false
<resultMap type="com.xxx.Employee" id="MyEmpByStep">
	 	<id column="id" property="id"/>
	 	<result column="last_name" property="lastName"/>
	 	<result column="email" property="email"/>
	 	<result column="gender" property="gender"/>
	 	<!-- association定义关联对象的封装规则
	 		select:表明当前属性是调用select指定的方法查出的结果,namesoace+方法名,当前mapper文件可以直接写方法名
	 		column:指定将哪一列的值传给这个方法
	 		流程:使用select指定的方法(传入column指定的这列参数的值)查出对象,并封装给property指定的属性
	 	 -->
 		<association property="dept" 
 		    select="com.xx.dao.DepartmentMapper.getDeptById" column="d_id">
 		</association>
	 </resultMap>
	 <!--  public Employee getEmpByIdStep(Integer id);-->
	 <select id="getEmpByIdStep" resultMap="MyEmpByStep">
	 	select * from tbl_employee where id=#{id}
	 </select>
	 
	 ....
    <mapper namespace="com.xx.dao.DepartmentMapper">
    	<!--public Department getDeptById(Integer id);  -->
    	<select id="getDeptById" resultType="com.xxx.Department">
    		select id,dept_name departmentName from tbl_dept where id=#{id}
    	</select>
	</mapper>

3.1 collection 一对多联合查询

<!-- 
	public class Department {
			private Integer id;
			private String departmentName;
			private List<Employee> emps;
	  did  dept_name  ||  eid  last_name  email   gender  
	 -->
	 
	<!--嵌套结果集的方式,使用collection标签定义关联的集合类型的属性封装规则  -->
	<resultMap type="com.xxx.Department" id="MyDept">
		<id column="did" property="id"/>
		<result column="dept_name" property="departmentName"/>
		<!-- 
			collection定义关联集合类型的属性的封装规则 
			ofType:指定集合里面元素的类型
		-->
		<collection property="emps" ofType="com.xxx.Employee">
			<!-- 定义这个集合中元素的封装规则 -->
			<id column="eid" property="id"/>
			<result column="last_name" property="lastName"/>
			<result column="email" property="email"/>
			<result column="gender" property="gender"/>
		</collection>
	</resultMap>
	<!-- public Department getDeptByIdPlus(Integer id); -->
	<select id="getDeptByIdPlus" resultMap="MyDept">
		SELECT d.id did,d.dept_name dept_name,
				e.id eid,e.last_name last_name,e.email email,e.gender gender
		FROM tbl_dept d
		LEFT JOIN tbl_employee e ON d.id=e.d_id
		WHERE d.id=#{id}
	</select>

3.2 collection 一对多分布联合查询

<resultMap type="com.xxx.Department" id="MyDeptStep">
		<id column="id" property="id"/>
		<id column="dept_name" property="departmentName"/>
		<collection property="emps" 
			select="com.xxx.dao.EmployeeMapperPlus.getEmpsByDeptId"
			column="{deptId=id}" fetchType="lazy"></collection>
	</resultMap>
	<!-- public Department getDeptByIdStep(Integer id); -->
	<select id="getDeptByIdStep" resultMap="MyDeptStep">
		select id,dept_name from tbl_dept where id=#{id}
	</select>
	
	<!-- 多个参数传递:
			将多列的值封装map传递;
			column="{key1=column1,key2=column2}"
			
		fetchType="" // 如果使用了,它将取代全局配置参数lazyLoadingEnabled。
    		- lazy:延迟 默认
    		- eager:立即
				
	 -->

4. 鉴别器 discriminator

可以使用discriminator判断某列的值,然后根据某列的值改变封装行为 如同switch case语句

1.
    <resultMap id="vehicleResult" type="Vehicle">
      <id property="id" column="id" />
      <result property="color" column="color"/>
      <discriminator javaType="int" column="vehicle_type">
        <case value="1" resultType="carResult">
          <result property="doorCount" column="door_count" />
        </case>
        <case value="2" resultType="truckResult">
          <result property="boxSize" column="box_size" />
        </case>
      </discriminator>
    </resultMap>


2.
 <resultMap type="com.xxx.Employee" id="MyEmpDis">
 	<id column="id" property="id"/>
 	<result column="last_name" property="lastName"/>
 	<!--
 		column:指定判定的列名
 		javaType:列值对应的java类型  -->
 	<discriminator javaType="string" column="gender">
 		<!--女生  resultType:指定封装的结果类型;不能缺少。/resultMap-->
 		<case value="0" resultType="com.axxxx.Employee">
 			<association property="dept" 
		 		select="com.xxx.dao.DepartmentMapper.getDeptById"
		 		column="d_id">
	 		</association>
 		</case>
 		<!--男生 ;如果是男生,把last_name这一列的值赋值给email; -->
 		<case value="1" resultType="com.xxx.Employee">
	 		<id column="id" property="id"/>
		 	<result column="last_name" property="lastName"/>
		 	<result column="last_name" property="email"/>
 		</case>
 	</discriminator>
 </resultMap>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值