myBatis(1)

官方帮助文档地址

1.如何使用mybatis

①.导入mybatis 和MySQL驱动的maven依耐

<dependencies>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.6</version>
    </dependency>
  </dependencies>

②.创建 java Bean

package bean;

public class Employee {
    private Integer id;
    private String lastName;
    private String gender;
    private String email;
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "bean.Employee{" +
                "id=" + id +
                ", lastName='" + lastName + '\'' +
                ", gender='" + gender + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

③创建Dao

package Dao;

import bean.Employee;

public interface EmployeeMapper {
    public Employee getEmpById(Integer id);
}

④.配置myBatis全局配置文件mybatis.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--1.properties
   url         :引入网络路径或者磁盘路径下的资源
   resource    :引入类路径下的资源
                  -->
    <properties  resource="conf/dbconfig.properties"></properties>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--对应sql映射文件路径-->
    <mappers>
        <mapper resource="conf/sql.xml"/>
    </mappers>
</configuration>

⑤.配置mybatis全局配置文件的sql映射文件sql.xml

<?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">
<!--
        namespace :名称空间,指定为接口的全类名
        id        :唯一标识
        resultType:返回值类型
        #{id}     :从传递过来的参数中取出id值
        -->
<mapper namespace="Dao.EmployeeMapper" >
    <!--id设置为getEmpById(名称空间接口的方法):该select标签为该接口中getEmpById(Integer id)方法的实现-->
    <select id="getEmpById" resultType="bean.Employee">
        select * from tbl_employee where id = #{id}
    </select>
</mapper>

⑥.配置dbconfig.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=qq2694200519

⑦.创建测试类MyBatisText2


import Dao.EmployeeMapper;
import bean.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisText2 {
    public static void main(String[] args) throws IOException {
        //1.获取myBatis全局配置文件的输入流
        InputStream inputStream = Resources.getResourceAsStream("conf/mybatis.xml");
        //2. 获取SqlSession工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //3.获取SqlSession对象
        SqlSession openSession=sqlSessionFactory.openSession();
        try {
            //4.获取端口的实现类对象:会为接口自动创建代理对象,由代理对象完成增删改查
            EmployeeMapper mapper=openSession.getMapper(EmployeeMapper.class);
            Employee employee=mapper.getEmpById(1);
            System.out.println(employee);
        }finally {
            //5.关闭openSession
        openSession.close();
        }
    }
}

⑧.运行测试类,控制台输出id为1的Employee

2.mybatis全局配置文件详解

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<!--
		1、mybatis可以使用properties来引入外部properties配置文件的内容;
		resource:引入类路径下的资源
		url:引入网络路径或者磁盘路径下的资源
	  -->
	<properties resource="dbconfig.properties"></properties>
	
	
	<!-- 
		2、settings包含很多重要的设置项
		setting:用来设置每一个设置项
			name:设置项名
			value:设置项取值
	 -->
	<settings>
		<setting name="mapUnderscoreToCamelCase" value="true"/>
	</settings>
	
	
	<!-- 3、typeAliases:别名处理器:可以为我们的java类型起别名 
			别名不区分大小写
	-->
	<typeAliases>
		<!-- 1、typeAlias:为某个java类型起别名
				type:指定要起别名的类型全类名;默认别名就是类名小写;employee
				alias:指定新的别名
		 -->
		<!-- <typeAlias type="com.atguigu.mybatis.bean.Employee" alias="emp"/> -->
		
		<!-- 2、package:为某个包下的所有类批量起别名 
				name:指定包名(为当前包以及下面所有的后代包的每一个类都起一个默认别名(类名小写),)
		-->
		<package name="com.atguigu.mybatis.bean"/>
		
		<!-- 3、批量起别名的情况下,使用@Alias注解为某个类型指定新的别名 -->
	</typeAliases>
		
	<!-- 
		4、environments:环境们,mybatis可以配置多种环境 ,default指定使用某种环境。可以达到快速切换环境。
			environment:配置一个具体的环境信息;必须有两个标签;id代表当前环境的唯一标识
				transactionManager:事务管理器;
					type:事务管理器的类型;JDBC(JdbcTransactionFactory)|MANAGED(ManagedTransactionFactory)
						自定义事务管理器:实现TransactionFactory接口.type指定为全类名
				
				dataSource:数据源;
					type:数据源类型;UNPOOLED(UnpooledDataSourceFactory)
								|POOLED(PooledDataSourceFactory)
								|JNDI(JndiDataSourceFactory)
					自定义数据源:实现DataSourceFactory接口,type是全类名
		 -->
		 

		 
	<environments default="dev_mysql">
		<environment id="dev_mysql">
			<transactionManager type="JDBC"></transactionManager>
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driver}" />
				<property name="url" value="${jdbc.url}" />
				<property name="username" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
			</dataSource>
		</environment>
	
		<environment id="dev_oracle">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${orcl.driver}" />
				<property name="url" value="${orcl.url}" />
				<property name="username" value="${orcl.username}" />
				<property name="password" value="${orcl.password}" />
			</dataSource>
		</environment>
	</environments>
	
	
	<!-- 5、databaseIdProvider:支持多数据库厂商的;
	
		 type="DB_VENDOR":VendorDatabaseIdProvider
		 	作用就是得到数据库厂商的标识(驱动getDatabaseProductName()),mybatis就能根据数据库厂商标识来执行不同的sql;
		 	MySQL,Oracle,SQL Server,xxxx
		 	在sql映射文件下通过databaseId指定要使用的数据库厂商
		 	<select id="getEmpById" resultType="bean.Employee" databaseId="oracle">
        select * from tbl_employee where id = #{id}
    </select>
	  -->
	<databaseIdProvider type="DB_VENDOR">
		<!-- 为不同的数据库厂商起别名 -->
		<property name="MySQL" value="mysql"/>
		<property name="Oracle" value="oracle"/>
		<property name="SQL Server" value="sqlserver"/>
	</databaseIdProvider>
	
	
	<!-- 将我们写好的sql映射文件(EmployeeMapper.xml)一定要注册到全局配置文件(mybatis-config.xml)中 -->
	<!-- 6、mappers:将sql映射注册到全局配置中 -->
	<mappers>
		<!-- 
			mapper:注册一个sql映射 
				注册配置文件
				resource:引用类路径下的sql映射文件
					mybatis/mapper/EmployeeMapper.xml
				url:引用网路路径或者磁盘路径下的sql映射文件
					file:///var/mappers/AuthorMapper.xml
					
				注册接口
				class:引用(注册)接口,
					1、有sql映射文件,映射文件名必须和接口同名,并且放在与接口同一目录下;
					2、没有sql映射文件,所有的sql都是利用注解写在接口对应的方法上;
					推荐:
						比较重要的,复杂的Dao接口我们来写sql映射文件
						不重要,简单的Dao接口为了开发快速可以使用注解;
		-->
		<!-- <mapper resource="mybatis/mapper/EmployeeMapper.xml"/> -->
		<!-- <mapper class="com.atguigu.mybatis.dao.EmployeeMapperAnnotation"/> -->
		
		<!-- 批量注册: -->
		<package name="com.atguigu.mybatis.dao"/>
	</mappers>
</configuration>

mappers:基于注解的方式
mybatis全局配置文件中

<!--无映射文件,所有sql都是利用注解写在接口对应的方法上-->
    <mappers>
        <mapper class="Dao.EmployeeMapper"/>
    </mappers>

对应接口

package Dao;

import bean.Employee;
import org.apache.ibatis.annotations.Select;

public interface EmployeeMapper {
    @Select("select * from tbl_employee where id = #{id}")
    public Employee getEmpById(Integer id);
}

测试类

import Dao.EmployeeMapper;
import bean.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisText2 {
    public static void main(String[] args) throws IOException {
        //1.获取myBatis全局配置文件的输入流
        InputStream inputStream = Resources.getResourceAsStream("conf/mybatis.xml");
        //2. 获取SqlSession工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //3.获取SqlSession对象
        SqlSession openSession=sqlSessionFactory.openSession();
        try {
            //4.获取端口的实现类对象:会为接口自动创建代理对象,由代理对象完成增删改查
            EmployeeMapper mapper=openSession.getMapper(EmployeeMapper.class);
            Employee employee=mapper.getEmpById(1);
            System.out.println(employee);
        }finally {
            //5.关闭openSession
        openSession.close();
        }
    }
}

3.MyBatis实现增删改查

Dao接口

package Dao;
import bean.Employee;
public interface EmployeeMapper {
    public Employee getEmpById(Integer id);

    public void delEmp(Integer id);
    public Integer  updEmp(Employee employee);
    public void addEmp(Employee employee);
}

sql映射文件

<!--parameterType可以省略-->
    <insert id="addEmp" parameterType="bean.Employee">
        INSERT INTO tbl_employee(last_name,gender,email)
         VALUES(#{last_name},#{gender},#{email})
    </insert>

    <delete id="delEmp">
DELETE FROM tbl_employee WHERE id=#{id}
    </delete>

 <update id="updEmp" parameterType="bean.Employee">
UPDATE tbl_employee SET
last_name=#{last_name},gender=#{gender},email =#{email}
WHERE id=3
 </update>

查询单条记录

 <select id="getEmpById" resultType="bean.Employee">
        select * from tbl_employee where id = #{id}
    </select>

测试

import Dao.EmployeeMapper;
import bean.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisText3 {
    public static void main(String[] args) throws IOException {
        InputStream in = Resources.getResourceAsStream("conf/mybatis.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        SqlSession openSession = sqlSessionFactory.openSession();
        try {
            //查询
            EmployeeMapper employeeMapper = openSession.getMapper(EmployeeMapper.class);
            System.out.println(employeeMapper.getEmpById(3));
            //删除
//            employeeMapper.delEmp(2);
            //增加
//           employeeMapper.addEmp(new Employee("aa","4","fdag41541"));
            //修改
            int b=employeeMapper.updEmp(new Employee(1000,"sft","3","fdad"));
            System.out.println(b);
            //提交
            openSession.commit();

        } finally {
            openSession.close();
        }
    }
}

查询多条记录
Dao中

public List<Employee> getEmps(Integer id);

sql映射文件中

 <!--返回List, resultType为集合中要放的元素-->
    <select id="getEmps" resultType="bean.Employee">
        select * from tbl_employee where id > #{id}
    </select>

测试

System.out.println(employeeMapper.getEmps(1));

查询单条记录的map
Dao

 //    @MapKey("id"):指定map的键为那一列
    @MapKey("id")
    public Map<String, Employee> getEmpMap(Integer id);

sql映射文件中

    <!--键是这条记录的主键,值是记录封装后的javaBean对象-->
<select id="getEmpMap" resultType="map">
   select * from tbl_employee where id = #{id}
</select>

测试

            Map<String, Employee> employeeMap = employeeMapper.getEmpMap(6);
            System.out.println(employeeMap.keySet());
            System.out.println(employeeMap.values());

查询多条记录的map
Dao

//    @MapKey("id"):指定map的键为那一列
    @MapKey("id")
    public Map<String, Employee> getEmpMaps(Integer id);

sql映射文件中

    <!--返回多条记录的map,键是这条记录的主键,值是记录封装后的javaBean对象-->
 <select id="getEmpMaps" resultType="bean.Employee">
        select * from tbl_employee where id > #{id}
    </select>

测试

 System.out.println(  employeeMapper.getEmpMaps(1));

补充

①. mybatis允许增删改直接定义以下类型返回值
(eg Integer定义为修改的返回值,修改多少条记录就返回多少条记录)
[ Integer,Long,Boolean]或其包装类,或基本类型
eg
接口中 修改的方法

 public Integer  updEmp(Employee employee);

测试类中

//修改
            int b=employeeMapper.updEmp(new Employee(1000,"sft","3","fdad"));
            System.out.println(b);

②.
sqlSessionFactory.openSession():手动提交
sqlSessionFactory.openSession(true):自动提交

③.获取自增主键
sql映射文件

    <!--useGeneratedKeys="true":使用自增主键获取主键值策略-->
    <!--keyProperty:mybatis获取主键值后,将这个值封装给javaBean的那个属性-->
    <insert id="addEmp" parameterType="bean.Employee"
    useGeneratedKeys="true" keyProperty="id">
        INSERT INTO tbl_employee(last_name,gender,email) 
        VALUES(#{last_name},#{gender},#{email})
    </insert>

测试

 Employee employee=new Employee("aa","4","fdag41541");
           employeeMapper.addEmp(employee);
            System.out.println(employee.getId());

4.mybatis参数处理

单个参数:mybatis不会做特殊处理,
#{参数名/任意名}:取出参数值。

多个参数:mybatis会做特殊处理。
多个参数会被封装成 一个map,
key:param1…paramN,或者参数的索引也可以
value:传入的参数值
#{}就是从map中获取指定的key的值;

异常:
org.apache.ibatis.binding.BindingException: 
Parameter 'id' not found. 
Available parameters are [1, 0, param1, param2]
操作:
	方法:public Employee getEmpByIdAndLastName(Integer id,String lastName);
	取值:#{id},#{lastName}

【命名参数】:明确指定封装参数时map的key;@Param(“id”)
多个参数会被封装成 一个map,
key:使用@Param注解指定的值
value:参数值
#{指定的key}取出对应的参数值

POJO:
如果多个参数正好是我们业务逻辑的数据模型,我们就可以直接传入pojo;
#{属性名}:取出传入的pojo的属性值

Map:
如果多个参数不是业务模型中的数据,没有对应的pojo,不经常使用,为了方便,我们也可以传入map
#{key}:取出map中对应的值

TO:
如果多个参数不是业务模型中的数据,但是经常要使用,推荐来编写一个TO(Transfer Object)数据传输对象
Page{
int index;
int size;
}

-------------------------------------思考-------------------------------------
public Employee getEmp(@Param(“id”)Integer id,String lastName);
取值:id==>#{id/param1} lastName==>#{param2}

public Employee getEmp(Integer id,@Param(“e”)Employee emp);
取值:id==>#{param1} lastName===>#{param2.lastName/e.lastName}

##特别注意:如果是Collection(List、Set)类型或者是数组,
也会特殊处理。也是把传入的list或者数组封装在map中。
key:Collection(collection),如果是List还可以使用这个key(list)
数组(array)
public Employee getEmpById(List ids);
取值:取出第一个id的值: #{list[0]}

----------结合源码,mybatis怎么处理参数---------------------------
总结:参数多时会封装map,为了不混乱,我们可以使用@Param来指定封装时使用的key;
#{key}就可以取出map中的值;

(@Param(“id”)Integer id,@Param(“lastName”)String lastName);
ParamNameResolver解析参数封装map的;
//1、names:{0=id, 1=lastName};构造器的时候就确定好了
确定流程:
1.获取每个标了param注解的参数的@Param的值:id,lastName; 赋值给name;
2.每次解析一个参数给map中保存信息:(key:参数索引,value:name的值)
name的值:
标注了param注解:注解的值
没有标注:
1.全局配置:useActualParamName(jdk1.8):name=参数名
2.name=map.size();相当于当前元素的索引
{0=id, 1=lastName,2=2}

args【1,“Tom”,‘hello’】:

public Object getNamedParams(Object[] args) {
final int paramCount = names.size();
//1、参数为null直接返回
if (args == null || paramCount == 0) {
return null;

//2、如果只有一个元素,并且没有Param注解;args[0]:单个参数直接返回
} else if (!hasParamAnnotation && paramCount == 1) {
  return args[names.firstKey()];
  
//3、多个元素或者有Param标注
} else {
  final Map<String, Object> param = new ParamMap<Object>();
  int i = 0;
  
  //4、遍历names集合;{0=id, 1=lastName,2=2}
  for (Map.Entry<Integer, String> entry : names.entrySet()) {
  
  	//names集合的value作为key;  names集合的key又作为取值的参考args[0]:args【1,"Tom"】:
  	//eg:{id=args[0]:1,lastName=args[1]:Tom,2=args[2]}
    param.put(entry.getValue(), args[entry.getKey()]);
    
    
    // add generic param names (param1, param2, ...)param
    //额外的将每一个参数也保存到map中,使用新的key:param1...paramN
    //效果:有Param注解可以#{指定的key},或者#{param1}
    final String genericParamName = GENERIC_NAME_PREFIX + String.valueOf(i + 1);
    // ensure not to overwrite parameter named with @Param
    if (!names.containsValue(genericParamName)) {
      param.put(genericParamName, args[entry.getKey()]);
    }
    i++;
  }
  return param;
}

}
}
--------------------------参数值的获取--------------------------
(1).
#{}:可以获取map中的值或者pojo对象属性的值;
: 可 以 获 取 m a p 中 的 值 或 者 p o j o 对 象 属 性 的 值 ; s e l e c t ∗ f r o m t b l e m p l o y e e w h e r e i d = {}:可以获取map中的值或者pojo对象属性的值; select * from tbl_employee where id= mappojoselectfromtblemployeewhereid={id} and last_name=#{lastName}
Preparing: select * from tbl_employee where id=2 and last_name=?
区别:
#{}:是以预编译的形式,将参数设置到sql语句中;PreparedStatement;防止sql注入
${}:取出的值直接拼装在sql语句中;会有安全问题;
大多情况下,我们去参数的值都应该去使用#{};

原生jdbc不支持占位符的地方我们就可以使用${}进行取值
比如分表、排序。。。;按照年份分表拆分
select * from ${year}_salary where xxx;
select * from tbl_employee order by ${f_name} ${order}

(2).#{}:更丰富的用法:
规定参数的一些规则:
javaType、 jdbcType、 mode(存储过程)、 numericScale、
resultMap、 typeHandler、 jdbcTypeName、 expression(未来准备支持的功能);
jdbcType通常需要在某种特定的条件下被设置:
在我们数据为null的时候,有些数据库可能不能识别mybatis对null的默认处理。比如Oracle(报错);
JdbcType OTHER:无效的类型;因为mybatis对所有的null都映射的是原生Jdbc的OTHER类型,oracle不能正确处理;

由于全局配置中:jdbcTypeForNull=OTHER;oracle不支持;两种办法
①.#{email,jdbcType=OTHER};
eg:
在这里插入图片描述
②.jdbcTypeForNull=NULL

<setting name="jdbcTypeForNull" value="NULL"/>

eg:
在这里插入图片描述

5.resultMap

<!--自定义某个javaBean的封装规则
	type:自定义规则的Java类型
	id:唯一id方便引用
	  -->
	<resultMap type="com.atguigu.mybatis.bean.Employee" id="MySimpleEmp">
		<!--指定主键列的封装规则
		id定义主键会底层有优化;
		column:指定哪一列
		property:指定对应的javaBean属性
		  -->
		<id column="id" property="id"/>
		<!-- 定义普通列封装规则 -->
		<result column="last_name" property="lastName"/>
		<!-- 其他不指定的列会自动封装:我们只要写resultMap就把全部的映射规则都写上。 -->
		<result column="email" property="email"/>
		<result column="gender" property="gender"/>
	</resultMap>
	
	<!-- resultMap:自定义结果集映射规则;  -->
	<!-- public Employee getEmpById(Integer id); -->
	<select id="getEmpById"  resultMap="MySimpleEmp">
		select * from tbl_employee where id=#{id}
	</select>

场景一
场景一:
查询Employee的同时查询员工对应的部门
Employee===Department
一个员工有与之对应的部门信息;
将雇员类的各属性包括部门类属性赋从数据库中查询到的值 ,三种方法
(1).联合查询在这里插入图片描述
(2).使用association定义关联的单个对象的封装规则;

resultMap标签中association
association对javaBean中的类属性的各个属性赋从数据库中查询到指定列的值
在这里插入图片描述
(3).分步查询
EmployeeMapperPlus.xml文件中

 <!-- 使用association进行分步查询:
		1、先按照员工id查询员工信息
		2、根据查询员工信息中的d_id值去部门表查出部门信息
		3、部门设置到员工中;
	 -->
	 
	 <!--  id  last_name  email   gender    d_id   -->
	 <resultMap type="com.atguigu.mybatis.bean.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指定的方法查出的结果
	 		column:指定将哪一列的值传给这个方法
	 		
	 		流程:使用select指定的方法(传入查出column指定的这列参数的值)查出对象,并封装给property指定的属性
	 	 -->
 		<association property="dept" 
	 		select="com.atguigu.mybatis.dao.DepartmentMapper.getDeptById"
	 		column="d_id">
 		</association>
	 </resultMap>
	 
<select id="getEmpByIdStep" resultMap="MyEmpByStep">
	 	select * from tbl_employee where id=#{id}
	 	</select>

Dao中

public Department getDeptById(Integer id);

DepartmentMapper.xml文件中

<!--public Department getDeptById(Integer id);  -->
	<select id="getDeptById" resultType="com.atguigu.mybatis.bean.Department">
		select id,dept_name departmentName from tbl_dept where id=#{id}
	</select>

在这里插入图片描述
在这里插入图片描述
场景二:
查询部门的时候将部门对应的所有员工信息也查询出来:注释在
DepartmentMapper.xml中

(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.atguigu.mybatis.bean.Department" id="MyDept">
		<id column="did" property="id"/>
		<result column="dept_name" property="departmentName"/>
		<!-- 
			collection定义关联集合类型的属性的封装规则 
			ofType:指定集合里面元素的类型
		-->
		<collection property="emps" ofType="com.atguigu.mybatis.bean.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>

(2).collection分步查询的方式
DepartmentMapper.xml文件中

<!-- collection:分段查询 -->
	<resultMap type="com.atguigu.mybatis.bean.Department" id="MyDeptStep">
		<id column="id" property="id"/>
		<id column="dept_name" property="departmentName"/>
		<collection property="emps" 
select="com.atguigu.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId"
			column="{deptId=id}" fetchType="lazy"></collection>
	</resultMap>
		<!-- 扩展:多列的值传递过去:
			将多列的值封装map传递;
			column="{key1=column1,key2=column2}"
		fetchType="lazy":表示使用延迟加载;
				- lazy:延迟
				- eager:立即
	 -->
	<!-- public Department getDeptByIdStep(Integer id); -->
	<select id="getDeptByIdStep" resultMap="MyDeptStep">
		select id,dept_name from tbl_dept where id=#{id}
	</select>
	

EmployeeMapperPlus.xml文件中

<!-- public List<Employee> getEmpsByDeptId(Integer deptId); -->
	<select id="getEmpsByDeptId" resultType="com.atguigu.mybatis.bean.Employee">
		select * from tbl_employee where d_id=#{deptId}
	</select>
	

(3).鉴别器

<discriminator javaType=""></discriminator>
	鉴别器:mybatis可以使用discriminator判断某列的值,然后根据某列的值改变封装行为
	封装Employee:
		如果查出的是女生:就把部门信息查询出来,否则不查询;
		如果是男生,把last_name这一列的值赋值给email;
 
 
 <resultMap type="com.atguigu.mybatis.bean.Employee" id="MyEmpDis">
 	<id column="id" property="id"/>
 	<result column="last_name" property="lastName"/>
 	<result column="email" property="email"/>
 	<result column="gender" property="gender"/>
 	<!--
 		column:指定判定的列名
 		javaType:列值对应的java类型  
 		-->
 	<discriminator javaType="string" column="gender">
 		<!--女生  resultType:指定封装的结果类型;不能缺少。/resultMap-->
 		<case value="0" resultType="com.atguigu.mybatis.bean.Employee">
 			<association property="dept" 
		 		select="com.atguigu.mybatis.dao.DepartmentMapper.getDeptById"
		 		column="d_id">
	 		</association>
 		</case>
 		<!--男生 ;如果是男生,把last_name这一列的值赋值给email; -->
 		<case value="1" resultType="com.atguigu.mybatis.bean.Employee">
	 		<id column="id" property="id"/>
		 	<result column="last_name" property="lastName"/>
		 	<result column="last_name" property="email"/>
		 	<result column="gender" property="gender"/>
 		</case>
 	</discriminator>
 </resultMap>

6. 动态sql

(1).if,where标签

    <!-- 查询员工,要求,携带了哪个字段查询条件就带上这个字段的值 -->
    <!-- public List<Employee> getEmpsByConditionIf(Employee e);-->
    <select id="getEmpsByConditionIf" resultType="bean.Employee">
        select * from tbl_employee
        <!-- where -->
        <where>
            <!-- test:判断表达式(OGNL)
            OGNL参照PPT或者官方文档。
                   c:if  test
            从参数中取值进行判断

            遇见特殊符号应该去写转义字符:
            &&:
            -->
            <if test="id!=null">
                id=#{id}
            </if>
            <if test="last_name!=null &amp;&amp; last_name!=&quot;&quot;">
                and last_name like #{last_name}
            </if>
            <if test="email!=null and email.trim()!=&quot;&quot;">
                and email=#{email}
            </if>
            <!-- ognl会进行字符串与数字的转换判断  "0"==0 -->
            <if test="gender==0 or gender==1">
                and gender=#{gender}
            </if>
        </where>
    </select>

注:
//查询的时候如果某些条件没带可能sql拼装会有问题
//1、给where后面加上1=1,以后的条件都and xxx.
//2、mybatis使用where标签来将所有的查询条件包括在内。mybatis就会将where标签中拼装的sql,多出来的and或者or去掉
//where只会去掉第一个多出来的and或者or。
所以建议每一个if标签中
这样形式写

  <if test="last_name!=null &amp;&amp; last_name!=&quot;&quot;">
                and last_name like #{last_name}
            </if>

而不是

  <if test="last_name!=null &amp;&amp; last_name!=&quot;&quot;">
                last_name like #{last_name}   and
            </if>

(2).trim标签

<!--public List<Employee> getEmpsByConditionTrim(Employee e);-->
	  <select id="getEmpsByConditionTrim" resultType="bean.Employee">
        select * from tbl_employee
	 	<!-- 后面多出的and或者or where标签不能解决 
	 	prefix="":前缀:trim标签体中是整个字符串拼串 后的结果。
	 			prefix给拼串后的整个字符串加一个前缀 
	 	prefixOverrides="":
	 			前缀覆盖: 去掉整个字符串前面多余的字符
	 	suffix="":后缀
	 			suffix给拼串后的整个字符串加一个后缀 
	 	suffixOverrides=""
	 			后缀覆盖:去掉整个字符串后面多余的字符
	 			
	 	-->
	 	<!-- 自定义字符串的截取规则 -->
	 	<trim prefix="where" suffixOverrides="and">
            <if test="id!=null">
                id=#{id}  and
            </if>
            <if test="last_name!=null &amp;&amp; last_name!=&quot;&quot;">
                 last_name like #{last_name} and
            </if>
            <if test="email!=null and email.trim()!=&quot;&quot;">
                 email=#{email} and
            </if>
            <!-- ognl会进行字符串与数字的转换判断  "0"==0 -->
            <if test="gender==0 or gender==1">
                gender=#{gender}
            </if>
        </trim>
    </select>

(3).choose (when, otherwise):分支选择;带了break的swtich-case

<!--测试choose (when, otherwise)标签-->
    <!--public List<Employee>getEmpsByConditionChoose(Employee e);-->
    <select id="getEmpsByConditionChoose" resultType="bean.Employee">
        select * from tbl_employee
        <where>
            <!-- 如果带了id就用id查,如果带了lastName就用lastName查;只会进入其中一个 -->
            <choose>
                <when test="id!=null">
                    id=#{id}
                </when>
                <when test="last_name !=null">
                    last_name like #{last_name }
                </when>
                <when test="email!=null">
                    email = #{email}
                </when>
                <otherwise>
                    gender = 0
                </otherwise>
            </choose>
        </where>
    </select>

(4).Set标签的使用
set标签,可智能去掉后面的 “,”

  <!--public int upDate(Employee e);-->
    <update id="upDate">
UPDATE tbl_employee
<set>
    <if test="last_name!=null">
        last_name=#{last_name},
    </if>
<if test="gender!=null">
    gender=#{gender},
</if>
    <if test="email!=null">
        email =#{email}
    </if>
</set>
WHERE id=#{id}
    </update>

补充:使用trim标签实现同样功能

  <!--public int upDate(Employee e);-->
 <update id="upDate">
        UPDATE tbl_employee
        <trim prefix="set" suffixOverrides=",">
            <if test="last_name!=null">
                last_name=#{last_name},
            </if>
            <if test="gender!=null">
                gender=#{gender},
            </if>
            <if test="email!=null">
                email =#{email}
            </if>
       </trim>
        WHERE id=#{id}
    </update>

(5).forEach标签

 <!--public List<Employee> 
 getEmpsByConditionForeach(@Param("ids")List<Integer> ids);
  -->
    <select id="getEmpsByConditionForeach" resultType="bean.Employee">
        select * from tbl_employee
        <!--
            collection:指定要遍历的集合:
                list类型的参数会特殊处理封装在map中,map的key就叫list
            item:将当前遍历出的元素赋值给指定的变量
            separator:每个元素之间的分隔符
            open:遍历出所有结果拼接一个开始的字符
            close:遍历出所有结果拼接一个结束的字符
            index:索引。遍历list的时候是index就是索引,item就是当前值
                          遍历map的时候index表示的就是map的key,item就是map的值

            #{变量名}就能取出变量的值也就是当前遍历出的元素
          -->
        <foreach collection="ids" item="item_id" separator=","
                 open="where id in(" close=")">
            #{item_id}
        </foreach>
    </select>

(6).批量保存

<!-- 批量保存 -->
    <!--public void addEmps(@Param("emps")List<Employee> emps);  -->
    <!--MySQL下批量保存:可以foreach遍历   mysql支持values(),(),()语法-->
    <insert id="addEmps">
        INSERT into tbl_employee(last_name,gender,email)
        values
    <foreach collection="emps" item="emp" separator=",">
         (#{emp.last_name},#{emp.email},#{emp.gender})
    </foreach>
    </insert>

补充

两个内置参数:
不只是方法传递过来的参数可以被用来判断,取值。。。
mybatis默认还有两个内置参数:
_parameter:代表整个参数
单个参数:_parameter就是这个参数
多个参数:参数会被封装为一个map;_parameter就是代表这个map
_databaseId:如果配置了databaseIdProvider标签。
_databaseId就是代表当前数据库的别名oracle

(7).bind标签

 <!--public List<Employee> getEmpsTestInnerParameter(Employee employee);  -->
    <select id="getEmpsTestInnerParameter" resultType="bean.Employee">
        <!-- bind:可以将OGNL表达式的值绑定到一个变量中,方便后来引用这个变量的值 -->
        <bind name="last_name" value="'%'+last_name+'%'"/>
            select * from tbl_employee
            <if test="_parameter!=null">
                where last_name like #{last_name}
            </if>
    </select>

(8).sql标签

 <!-- 
	  	抽取可重用的sql片段。方便后面引用 
	  	1、sql抽取:经常将要查询的列名,或者插入用的列名抽取出来方便引用
	  	2、include来引用已经抽取的sql:
	  	3、include还可以自定义一些property,sql标签内部就能使用自定义的属性
	  			include-property:取值的正确方式${prop},
	  			#{不能使用这种方式}
	  -->
	  <insert id="addEmps">
        INSERT into tbl_employee(<include refid="insertColumn"></include>)
        values
    <foreach collection="emps" item="emp" separator=",">
         (#{emp.last_name},#{emp.email},#{emp.gender})
    </foreach>
    </insert>
	  <sql id="insertColumn">
	  			last_name,email,gender,d_id
	  </sql>

7.缓存

(1).一级缓存

sqlSession级别的缓存。一级缓存是一直开启的;SqlSession级别的一个Map
* 与数据库同一次会话期间查询到的数据会放在本地缓存中。
* 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库;
*
* 一级缓存失效情况(没有使用到当前一级缓存的情况,效果就是,还需要再向数据库发出查询):
* 1、sqlSession不同。
* 2、sqlSession相同,查询条件不同.(当前一级缓存中还没有这个数据)
* 3、sqlSession相同,两次查询之间执行了增删改操作(这次增删改可能对当前数据有影响)
* 4、sqlSession相同,手动清除了一级缓存
* 缓存清空: openSession.clearCache();
*
(2).二级缓存
* 二级缓存:(全局缓存):基于namespace级别的缓存:一个namespace对应一个二级缓存:
* 工作机制
* 1、一个会话,查询一条数据,这个数据就会被放在当前会话的一级缓存中;
* 2、如果会话关闭;一级缓存中的数据会被保存到二级缓存中;新的会话查询信息,就可以参照二级缓存中的内容;
* 3、sqlSession=EmployeeMapper>Employee
* DepartmentMapper===>Department
* 不同namespace查出的数据会放在自己对应的缓存中(map)
* 效果:数据会从二级缓存中获取
* 查出的数据都会被默认先放在一级缓存中。
* 只有会话提交或者关闭以后,一级缓存中的数据才会转移到二级缓存中
* 使用:
* 1)、开启全局二级缓存配置:
* 2)、去mapper.xml中配置使用二级缓存: <cache></cache>

	<!-- <cache eviction="FIFO" flushInterval="60000" readOnly="false" size="1024"></cache> -->
	<!--  
	eviction:缓存的回收策略:
		• LRU – 最近最少使用的:移除最长时间不被使用的对象。
		• FIFO – 先进先出:按对象进入缓存的顺序来移除它们。
		• SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。
		• WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
		• 默认的是 LRU。
	flushInterval:缓存刷新间隔
		缓存多长时间清空一次,默认不清空,设置一个毫秒值
	readOnly:是否只读:
		true:只读;mybatis认为所有从缓存中获取数据的操作都是只读操作,不会修改数据。
				 mybatis为了加快获取速度,直接就会将数据在缓存中的引用交给用户。不安全,速度快
		false:非只读:mybatis觉得获取的数据可能会被修改。
				mybatis会利用序列化&反序列的技术克隆一份新的数据给你。安全,速度慢
	size:缓存存放多少元素;
	
	
	type="":指定自定义缓存的全类名;
	实现Cache接口即可;

3)、我们的POJO需要实现序列化接口implements Serializable

和缓存有关的设置/属性:
* 1)、cacheEnabled=true:false:关闭缓存(二级缓存关闭)(一级缓存一直可用的)
* 2)、每个select标签都有useCache=“true”:
* false:不使用缓存(一级缓存依然使用,二级缓存不使用)
* 3)、【每个增删改标签的:flushCache=“true”:(一级二级都会清除)】
* 增删改执行完成后就会清楚缓存;
* 测试:flushCache=“true”:一级缓存就清空了;二级也会被清除;
* 查询标签:flushCache=“false”:
* 如果flushCache=true;每次查询之后都会清空缓存;缓存是没有被使用的;
* 4)、sqlSession.clearCache();只是清楚当前session的一级缓存;
* 5)、localCacheScope:本地缓存作用域:(一级缓存SESSION);当前会话的所有数据保存在会话缓存中;
* STATEMENT:可以禁用一级缓存;

缓存原理示意图
在这里插入图片描述
*第三方缓存整合:
* 1)、导入第三方缓存包即可;
* 2)、导入与第三方缓存整合的适配包;官方有;
* 3)、mapper.xml中使用自定义缓存
*

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值