导包
配置文件
全局配置文件
mybatis的全局配置文件:包含数据库连接池信息,事务管理器信息等…系统运行环境信息
mybatis-config.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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="0930" />
</dataSource>
</environment>
</environments>
<!-- 将我们写好的sql映射文件(EmployeeMapper.xml)一定要注册到全局配置文件(mybatis-config.xml)中 -->
<mappers>
<mapper resource="EmployeeMapper.xml" />
</mappers>
</configuration>
下面我们来总结一个全局配置文件用到的一些属性
这些属性在配置文件中的先后顺序要严格按照下图从上到下的顺序
properties 引入外部属性
mybatis可以使用properties来引入外部properties配置文件的内容;
- resource:引入类路径下的资源
- url:引入网络路径或者磁盘路径下的资源
<properties resource="dbconfig.properties"></properties>
dbconfig.properties内容:
mybatis-config.xml配置文件的修改:
settings
settings设置包含很多重要的设置项,会改变MyBatis 的运行时行为。
- 开启驼峰命名 mapUnderscoreToCamelCase
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
typeAliases 别名
typeAliases:别名处理器:可以为我们的java类型起别名
别名不区分大小写
-
typeAlias 为某个java类型起别名
type:指定要起别名的类型全类名;默认别名就是类名小写;employee
alias:指定新的别名<typeAliases> <typeAlias type="com.flora.mybatis.bean.Employee" alias="emp"></typeAlias> </typeAliases>
-
package:为某个包下的所有类批量起别名
name:指定包名(为当前包以及下面所有的后代包的每一个类都起一个默认别名(类名小写),)
<typeAliases> <package name="com.flora.mybatis.bean"/> </typeAliases>
批量起别名的情况下为防止bean包下还有子包的类名和bean下的类名一样,可以,使用@Alias注解为某个类型指定新的别名
typeHandlers 类型处理器
架起java类型和数据库类型一一映射的桥梁
plugins 插件
environments
- environments:环境们,mybatis可以配置多种环境 ,default指定使用某种环境。可以达到快速切换环境。
- environment:配置一个具体的环境信息;必须包含transactionManager和dataSource两个标签;id代表当前环境的唯一标识
-
transactionManager:事务管理器;
type:事务管理器的类型;
JDBC(JdbcTransactionFactory)|MANAGED(ManagedTransactionFactory)
自定义事务管理器:实现TransactionFactory接口.type指定为全类名 -
dataSource:数据源;
type:数据源类型;
UNPOOLED(UnpooledDataSourceFactory)
|POOLED(PooledDataSourceFactory)
|JNDI(JndiDataSourceFactory)
自定义数据源:实现DataSourceFactory接口,type是全类名
databaseIdProvider 多数据库厂商支持
type=“DB_VENDOR”:VendorDatabaseIdProvider
作用就是得到数据库厂商的标识(驱动getDatabaseProductName()),mybatis就能根据数据库厂商标识来执行不同的sql;
MySQL,Oracle,SQL Server,xxxx
<databaseIdProvider type="DB_VENDOR">
<!-- 为不同的数据库厂商起别名 -->
<property name="MySQL" value="mysql"/>
<property name="Oracle" value="oracle"/>
<property name="SQL Server" value="sqlserver"/>
</databaseIdProvider>
然后在EmployeeMapper.xml文件的select标签的databaseId属性 指定所用的数据库厂商
mappers sql映射注册
- mappers的作用就是将sql映射注册到全局配置中
- mappers的属性:
- resource:注册配置文件,引用类路径下的sql映射文件
- url:注册配置文件,引用网路路径或者磁盘路径下的sql映射文件
- class:引用(注册)接口,
注册接口
<mappers>
<mapper class="com.flora.mybatis.dao.EmployeeMapperAnnotation"/>
</mappers>
在EmployeeMapperAnnotation接口上利用注解写sql
批量注册
<mappers>
<!-- 批量注册: -->
<package name="com.atguigu.mybatis.dao"/>
</mappers>
sql映射文件
保存了每一个sql语句的映射信息:将sql抽取出来。
映射文件的作用就相当于是定义Dao接口的实现类如何
工作
EmployeeMapper.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">
<mapper namespace="com.flora.mybatis.dao.EmployeeMapper">
<!--
namespace:名称空间;指定为接口的全类名
id:唯一标识
resultType:返回值类型
#{id}:从传递过来的参数中取出id值
public Employee getEmpById(Integer id);
-->
<select id="getEmpById" resultType="com.flora.mybatis.bean.Employee">
select id,last_name lastName,gender,email from tbl_employee where id = #{id}
</select>
</mapper>
映射文件指导着MyBatis如何进行数据库增删改查,下面总结标签
增删改
- 接口中定义增删改的方法
Mybatis允许增删改直接定义Integer、Long、Boolean、void返回值类型,这里我们都写的void
- 映射文件EmployeeMapper.xml 定义sql语句
有 insert、update、delete标签<mapper namespace="com.flora.mybatis.dao.EmployeeMapper"> <!-- namespace:名称空间;指定为接口的全类名 id:唯一标识 resultType:返回值类型 #{id}:从传递过来的参数中取出id值 public Employee getEmpById(Integer id); --> <select id="getEmpById" resultType="com.flora.mybatis.bean.Employee"> select * from tbl_employee where id = #{id} </select> <!--public void addEmp(Employee employee);--> <insert id="addEmp" parameterType="com.flora.mybatis.bean.Employee"> insert into tbl_employee(last_name,email,gender) values (#{lastName},#{email},#{gender}) </insert> <!--public void updateEmp(Employee employee);--> <update id="updateEmp"> update tbl_employee set last_name=#{lastName},email=#{email},gender=#{gender} where id=#{id} </update> <!--public void deleteEmpById(Integer id);--> <delete id="deleteEmpById"> delete from tbl_employee where id=#{id} </delete> </mapper>
- 测试类测试
注意:因为增删改的结果必须要提交,如果我们用的openSession()是无参的,则不会自动提交数据。我们需要手动提交。
如果我们openSession(true) 则就会自动提交数据
获取自增主键值
- mysql支持自增主键,自增主键值的获取,mybatis也是利用statement.getGenreatedKeys();
- 我们需要在EmployeeMapper.xml 的标签中加入两个属性useGeneratedKeys和keyProperty
- useGeneratedKeys=“true”;使用自增主键获取主键值策略
- keyProperty;指定对应的主键属性,也就是mybatis获取到主键值以后,将这个值封装给javaBean的哪个属性
这样就可以在插入一条元素后,获取到主键的值了
<insert id="addEmp" parameterType="com.atguigu.mybatis.bean.Employee"
useGeneratedKeys="true" keyProperty="id" databaseId="mysql">
insert into tbl_employee(last_name,email,gender)
values(#{lastName},#{email},#{gender})
</insert>
参数处理
单个参数
单个参数:mybatis不会做特殊处理,
#{参数名/任意名}:取出参数值。
多个参数 & 命名参数
- 多个参数:mybatis会做特殊处理。
- 多个参数会被封装成 一个map,
key:param1…paramN,或者参数的索引也可以
value:传入的参数值
所以我们在取参数值的时候要写成@{param1},@{param2}
- Collection(List、Set)类型或者是数组,
也会特殊处理。也是把传入的list或者数组封装在map中。
key:Collection(collection),如果是List还可以使用这个key(list)
数组(array)
public Employee getEmpById(List ids);
取值:取出第一个id的值:#{list[0]}
- 命名参数:
明确指定封装参数时map的key;@Param(“id”)
多个参数会被封装成 一个map,
key:使用@Param注解指定的值
value:参数值
#{指定的key}取出对应的参数值
POJO & Map
- POJO:
如果多个参数正好是我们业务逻辑的数据模型,我们就可以直接传入pojo;
#{属性名}:取出传入的pojo的属性值
- Map:
如果多个参数不是业务模型中的数据,没有对应的pojo,不经常使用,为了方便,我们也可以传入map
#{key}:取出map中对应的值
TO(Transfer Object)数据传输对象
如果多个参数不是业务模型中的数据,但是经常要使用,推荐来编写一个TO(Transfer Object)数据传输对象
如分页的page对象
Page{
int index;
int size;
}
参数处理源码分析
对于接口中定义的getEmpByIdAndLastName()方法
public Employee getEmpByIdAndLastName(@Param("id")Integer id,@Param("lastName")String lastName);
测试时查询的方法:
Employee employee = mapper.getEmpByIdAndLastName(1, "Tom");
-
我们传进来的args时通过convertArgsToSqlCommandParam()方法转换成sql执行的参数的,具体怎么转看下面
convertArgsToSqlCommandParam()方法: -
ParamNameResolver解析参数封装map的;
首先paramNameResolver() 构造器确定names的值
ParamNameResolver的getNameParams()方法具体流程
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;
}
}
}
#{}和${}
#{}和${}都可以获取map中的值或者pojo对象属性的值,区别在于
select * from tbl_employee where id=${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}
#{}
#{}可以规定参数的一些规则:
javaType、 jdbcType、 mode(存储过程)、 numericScale、
resultMap、 typeHandler、 jdbcTypeName、 expression(未来准备支持的功能);
jdbcType使用的示例:
在我们数据为null的时候,有些数据库可能不能识别mybatis对null的默认处理。比如Oracle。
因为jdbcTypeForNull=OTHER;oracle不支持
这时我们就可以用#{email,jdbcType=NULL}
或者用<setting标签 在全局配置中设置jdbcTypeForNull=NULL:
<setting name="jdbcTypeForNull" value="NULL"/>
select
resultType
resultType: 返回值类型。
resultType 指的是对于返回的每一条记录要返回什么类型,因此return的是list、map里装很多记录 ,那resultType里写的是装的那些记录的类型,而不是写list ,map。
resultType属性不能和resultMap同时使用
返回List
resultType: 如果返回的是一个集合,要写集合中元素的类型
记录封装map
- 单条记录的封装
resultType: 如果要返回map,则写map。因为只有一条记录,这条记录返回成map
查询结果的列名为map的key,值为map的value
- 多条记录的封装
多条记录封装一个map:Map<Integer,Employee>:键是这条记录的主键,值是记录封装后的javaBean
@MapKey
:告诉mybatis封装这个map的时候使用哪个属性作为map的key
resultType: 写map中放的元素的类型
resultMap
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
一个员工有与之对应的部门信息;
id last_name gender d_id did dept_name (private Department dept;)
<!-- public Employee getEmpAndDept(Integer id);-->
<select id="getEmpAndDept" resultMap="MyDifEmp">
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>
方法一:用级联属性封装结果集
<!--
联合查询:级联属性封装结果集
-->
<resultMap type="com.atguigu.mybatis.bean.Employee" id="MyDifEmp">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="gender" property="gender"/>
<result column="did" property="dept.id"/>
<result column="dept_name" property="dept.departmentName"/>
</resultMap>
association 关联对象类型的属性的封装规则
-
方法二:使用association定义关联的单个对象的封装规则;
<!-- 使用association定义关联的单个对象的封装规则; --> <resultMap type="com.atguigu.mybatis.bean.Employee" id="MyDifEmp2"> <id column="id" property="id"/> <result column="last_name" property="lastName"/> <result column="gender" property="gender"/> <!-- association可以指定联合的javaBean对象 property="dept":指定哪个属性是联合的对象 javaType:指定这个属性对象的类型[不能省略] --> <association property="dept" javaType="com.atguigu.mybatis.bean.Department"> <id column="did" property="id"/> <result column="dept_name" property="departmentName"/> </association> </resultMap>
-
方法三:使用association进行分步查询
<!-- 使用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> <!-- public Employee getEmpByIdStep(Integer id);--> <select id="getEmpByIdStep" resultMap="MyEmpByStep"> select * from tbl_employee where id=#{id} <if test="_parameter!=null"> and 1=1 </if> </select>
这样就可以实现延迟加载(懒加载);(按需加载):
我们每次查询Employee对象的时候,都将一起查询出来。
部门信息在我们使用的时候再去查询;
在分段查询的基础上,我们还需要加上两个配置:<!--显示的指定每个我们需要更改的配置的值,即使他是默认的。防止版本更新带来的问题 --> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/>
collection 关联集合类型的属性的封装规则
场景二:
查询部门的时候将部门对应的所有员工信息(是放在list集合里的)也查询出来
这就用到了collection,collection是定义关联集合类型的属性的封装规则
collection 的一些属性应用:
- 多列的值传递过去:
将多列的值封装map传递;
column="{key1=column1,key2=column2}"
-fetchType="lazy"
:表示使用延迟加载;
- lazy:延迟
- eager:立即
-
方式一:嵌套结果集的方式
<!-- 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>
定义封装规则
<!-- 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>
-
方式二:使用collection 分步查询
首先select语句<!-- public Department getDeptByIdStep(Integer id); --> <select id="getDeptByIdStep" resultMap="MyDeptStep"> select id,dept_name from tbl_dept where id=#{id} </select>
resultMap定义封装规则
<!-- 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>
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>
接口式编程
原生: Dao ====> DaoImpl
mybatis: Mapper ====> xxMapper.xml
- bean下的Employee 类和数据库对应
- dao下的EmployeeMapper接口是用来定义
- test下的MyBatisTest 写下面的东西
EmployeeMapper接口
通过接口定义规范,这样就不会像传统方法一样什么参数都能传进去,我们通过接口就可以规定传入的参数类型和返回的参数值类型。
通过在配置文件中和接口关联, 配置文件可以为此接口实现一个代理对象,最终我们是通过代理对象来调用接口的方法的。
test下的MyBatisTest.java
步骤:
- 创建一个SqlSessionFactory对象
根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象 有数据源一些运行环境信息
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
}
- 获取sqlSession对象
使用sqlSession工厂,获取到sqlSession对象使用他来执行增删改查。
一个sqlSession就是代表和数据库的一次会话,用完必须关闭关闭。 - 获取接口的实现类对象
- 通过接口的实现类对象调方法得到结果
- 关闭sqlSession
@Test
public void test01() throws IOException{
//1. 获取sqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
//2. 获取sqlSession对象
SqlSession openSession = sqlSessionFactory.openSession();
//3. 获取接口的实现类对象
try {
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);//为接口实现一个代理对象
// 4. 通过接口的实现类对象调方法得到结果
Employee employee = mapper.getEmpById(1);
System.out.println(employee);
} finally {
// 5. 关闭sqlSession
openSession.close();
}
}
不使用接口实现
/**
* 1、根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象 有数据源一些运行环境信息
* 2、sql映射文件;配置了每一个sql,以及sql的封装规则等。
* 3、将sql映射文件注册在全局配置文件中
* 4、写代码:
* 1)、根据全局配置文件得到SqlSessionFactory;
* 2)、使用sqlSession工厂,获取到sqlSession对象使用他来执行增删改查
* 一个sqlSession就是代表和数据库的一次会话,用完关闭
* 3)、使用sql的唯一标志来告诉MyBatis执行哪个sql。sql都是保存在sql映射文件中的。
*
* @throws IOException
*/
@Test
public void test() throws IOException {
// 2、获取sqlSession实例,能直接执行已经映射的sql语句
// sql的唯一标识:statement Unique identifier matching the statement to use.
// 执行sql要用的参数:parameter A parameter object to pass to the statement.
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try {
Employee employee = openSession.selectOne(
"com.atguigu.mybatis.EmployeeMapper.selectEmp", 1);
System.out.println(employee);
} finally {
openSession.close();
}
}