简介
MyBatis是一款开源的持久层框架,其使用了对象关系映射模式,通过对 JDBC 的封装,简化了程序猿的数据库操作,在国内使用较为广泛。
全局配置(环境搭建)
<?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>
<!--default属性是指默认使用的数据库的id(因为environment可以配置多个)-->
<environments default="mysql">
<!--mysql的运行环境-->
<environment id="mysql">
<!--事务类型-->
<transactionManager type="JDBC"/>
<!--连接池以及一些默认的配置信息-->
<dataSource type="POOLED">
<!--数据库驱动-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!--url-->
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<!--用户名-->
<property name="username" value="root"/>
<!--密码-->
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--关系映射-->
<mappers>
<!--设置所写的xml文件-->
<mapper resource="com/zw/mybatis/mapper/UserMapper.xml"/>
</mappers>
</configuration>
全局配置用来设置数据库访问的参数,以及映射对象的路径等信息
1.全局配置文件中内容
1.1 type 属性可取值
1.1.1 JDBC,事务管理使用 JDBC 原生事务管理方式
1.1.2 MANAGED 把事务管理转交给其他容器.原生 JDBC 事务 setAutoMapping(false);
1.2 type 属性
1.2.1 POOLED 使用数据库连接池
1.2.2 UNPOOLED 不实用数据库连接池,和直接使用 JDBC 一样
1.2.3 JNDI :java 命名目录接口技术
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">
<!--namespace里的名字是可以随便取的,但是最好遵照一定的规则,可以将其看作是Dao接口的一个实现类-->
<mapper namespace="com.zw.mybatis.mapper.UserMapper">
<!--这里的id是指方法名称,resultType是指某一行记录映射的对象的类型,因ResultSet一次只能读一行-->
<select id="sortAll" resultType="com.zw.mybatis.domain.User">
select * from users
</select>
</mapper>
以上只是简单的介绍,后续在详细展开说明
测试Mapper
public static void main(String[] args) throws IOException {
//Resources类是MyBatis专门用来获取配置文件的一个类
InputStream stream = Resources.getResourceAsStream("mybatis.xml");
//使用创建者模式创建SqlSession工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(stream);
//使用工厂获取SqlSession的一个实例
SqlSession session = factory.openSession();
//通过namespace以及id执行查询操作
User all = session.selectOne("com.zw.mybatis.mapper.UserMapper.sortAll");
System.out.println(all.getUsername());
}
注意
在使用IDEA构建Maven项目后,如果发现无法找到文件的问题,需要在pom.xml中添加如下代码(Build下)
<resources>
<!--意思是说可以在java下面的文件夹中存放xml文件-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
三种查询方式(未使用接口绑定时使用)
查询多个元素(集合)
-
selectList() 返回值为 List
-
适用于查询结果都需要遍历的需求
List<Flower> list = session.selectList("a.b.selAll");
查询单个元素
-
selectOne() 返回值 Object
-
适用于返回结果只是变量或一行数据时
int count = session.selectOne("a.b.selById");
查询结果为Map
-
selectMap() 返回值 Map
-
适用于需要在查询结果中通过某列的值取到这行数据的需求
Map<Object, Object> map = session.selectMap("a.b.c","name123");
其中第二个参数为键的名称,返回值中值既可以为map集合(将resultType设置为“map”),也可以为具体的实体类。
parameterType 属性
在 XXXMapper.xml 中、等标签的 parameterType 可以 控制参数类型。SqlSession 的 selectList()和 selectOne()的第二个参数和 selectMap() 的第三个参数都表示方法的参数.
示例:
java代码:
//查询单个结果
User user = session.selectOne("com.zw.mybatis.mapper.UserMapper.sortOne", "zhang");
xml代码:
<select id="sortOne" resultType="com.zw.mybatis.domain.User" parameterType="java.lang.String">
select * from users where username = #{0}
</select>
在 Mapper.xml 中可以通过#{}获取参数
-
parameterType 控制参数类型
-
#{}获取参数内容
-
使用索引,从 0 开始 #{0}表示第一个参数
<select id="sortOne" resultType="com.zw.mybatis.domain.User" parameterType="java.lang.String"> select * from users where username = #{0} </select>
-
也可以使用#{param1}表示第一个参数
<select id="sortOne" resultType="com.zw.mybatis.domain.User" parameterType="java.lang.String"> select * from users where username = #{username1} </select>
-
如果只有一个参数(基本数据类型或 String),mybatis 对#{}里面内容没有要求只要写内容即可
<select id="sortOne" resultType="com.zw.mybatis.domain.User" parameterType="java.lang.String"> select * from users where username = #{随便写} </select>
-
如果参数是对象,则#{属性名}
<select id="selectByObject" resultType="com.zw.mybatis.domain.User" parameterType="com.zw.mybatis.domain.User"> select * from users where username = #{username} </select>
-
如果参数是 map 写成#{key}
-
如果有多个参数,可以使用map或者对象类型进行参数传
-
MyBatis起别名
在使用MyBatis进行开发的过程中,可能经常需要返回一个实体类作为对象,但是在xml中需要将类的完整名称写出来,比较麻烦,因此我们可以在MyBatis的全局配置文件中添加配置,给这些类其别名,从而简化操作。
系统内置的别名
比如Map可以写成map,就是将英文全部换成小写的。
为某一个特定的类起别名
全局配置
<?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>
<settings>
<!--添加log4j日志支持-->
<setting name="logImpl" value="LOG4J"/>
</settings>
<typeAliases>
<!--为某一个特定的类起别名,这样在使用时就不用在写完整的路径了-->
<typeAlias type="com.zw.mybatis.domain.User" alias="User"/>
</typeAliases>
<!--default属性是指默认使用的数据库的id(因为environment可以配置多个)-->
<environments default="mysql">
<!--mysql的运行环境-->
<environment id="mysql">
<!--事务类型-->
<transactionManager type="JDBC"/>
<!--连接池以及一些默认的配置信息-->
<dataSource type="POOLED">
<!--数据库驱动-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!--url-->
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<!--用户名-->
<property name="username" value="root"/>
<!--密码-->
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--关系映射-->
<mappers>
<!--设置所写的xml文件-->
<mapper resource="com/zw/mybatis/mapper/UserMapper.xml"/>
</mappers>
</configuration>
实现类xml
<select id="selectByObject" resultType="User" parameterType="com.zw.mybatis.domain.User">
select * from users where username = '${username}'
</select>
为某一个包下的所有类起别名
这样每个类在使用时就直接写类名就行了
<typeAliases>
<!--只有一个属性,为这一个属性赋值即可,值即为包名-->
<!--<typeAlias type="com.zw.mybatis.domain.User" alias="User"/>-->
<package name="com.zw.mybatis.domain"/>
</typeAliases>
mybatis接口绑定技术以及多参数实现
在之前使用多参数时只能通过map或者对象传递,这种方式比较麻烦,同时,我们在使用mybatis时每次都要写完整的namespace也比较麻烦,因此我们需要通过mybatis提供的接口绑定技术对开发进行简化。其底层是通过动态代理来实现的。
-
作用:实现创建一个接口后把mapper.xml由mybatis生成接口的实现类,通过调用接口对象就可以获取 mapper.xml 中编写的 sql。
-
实现步骤:
- 创建一个接口
- 接口包名和接口名与 mapper.xml 中namespace
相同 - 接口中方法名和 mapper.xml 标签的 id 属性相同
- 接口包名和接口名与 mapper.xml 中namespace
- 在 mybatis.xml 中使用进行扫描接口和 mapper.xml
- 创建一个接口
-
代码实现
-
全局配置文件
<mappers> <!--设置所写的xml文件--> <!-- <mapper resource="com/zw/mybatis/mapper/UserMapper.xml"/>--> <package name="com.zw.mybatis.mapper"/> </mappers>
-
接口设计(其完整的类路径必须和映射的xml文件的namespace属性的值相同)
package com.zw.mybatis.mapper; import com.zw.mybatis.domain.User; import java.util.List; public interface UserMapper { public List<User> selectPages(int pageStart,int pageSize); public int selTotalCount(); }
-
mapper.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.zw.mybatis.mapper.UserMapper"> <!--不用在写参数--> <select id="selectPages" resultType="User"> <!--基本类型参数可以用0,1,2表示也可以用param1,param2表示--> select * from users limit #{param1},#{param2} </select> <select id="selTotalCount" resultType="int"> select count(*) from users </select> </mapper>
-
MyBatis缓存技术
在进行数据库查询过程中,我们有时会对一个相同的sql语句进行多次查询,这些查询都是重复的,因此我们可以使用MyBatis缓存技术,这样下一次在使用相同的sql语句进行查询时就直接通过缓存进行查询就行了。但是需要注意的是,缓存只针对查询。
- MyBatis 中默认 SqlSession 缓存开启
- 同一个 SqlSession 对象调用同一个时,只有第一次访问数据库,第一次之后把查询结果缓存到 SqlSession 缓存区(内存)中
- 缓存的是 statement 对象(简单记忆必须是用一个)
- 在 myabtis 时一个对应一个 statement 对象
- 有效范围必须是同一个 SqlSession 对象
缓存流程
-
步骤一: 先去缓存区中找是否存在 statement
-
步骤二:返回结果
-
步骤三:如果没有缓存 statement 对象,去数据库获取数据
-
步骤四:数据库返回查询结果
-
步骤五:把查询结果放到对应的缓存区中
-
示例
@Test public void fun1() throws IOException { InputStream inputStream = Resources.getResourceAsStream("mybatis.xml"); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = factory.openSession(); UserMapper userMapper = session.getMapper(UserMapper.class); User user = userMapper.sortAll("zhang"); User user2 = userMapper.sortAll("zhang"); System.out.println(user+":::"+user2); }
控制台log4j输出结果
org.apache.ibatis.logging.jdbc.BaseJdbcLogger DEBUG 2020-03-12 11:54:47 ==> Preparing: select * from users where username = ?; org.apache.ibatis.logging.jdbc.BaseJdbcLogger DEBUG 2020-03-12 11:54:47 ==> Parameters: zhang(String) org.apache.ibatis.logging.jdbc.BaseJdbcLogger DEBUG 2020-03-12 11:54:47 <== Total: 1 User{username='zhang', password='123456', type=3}:::User{username='zhang', password='123456', type=3}
可以看出select只执行了一次。
SqlSessionFactory 缓存(二级缓存)
有效范围:同一个 factory 内哪个 SqlSession 都可以获取
什么时候使用二级缓存:
当数据频繁被使用,很少被修改
使用二级缓存步骤
-
在 mapper.xml 中添加
-
如果不写 readOnly=”true”需要把实体类序列化
<cache readOnly="true"></cache>
-
当 SqlSession 对象 close()时或 commit()时会把 SqlSession 缓存的数据刷(flush)到 SqlSessionFactory 缓存区中
MyBatis动态SQL技术
MyBatis通过自定义的标签来完成动态SQL。
注意事项:
test里参数的写法
- 如果参数为对象类型(或者Map类型)的值,那么直接在里面写实体类中的名称就行了
<select id="getStudent" resultType="Student"> select * from student <where> <if test="sid != 0"> sid = #{sid} </if> <if test="stuName != null"> and stuname = #{stuName} </if> </where> </select>
如果是基本数据类型
如果只有一个参数
那么可以直接使用#{0}取出参数,但是test中需要写arg0或者param1
如果有多个基本数据类型的值
那么可以使用arg0(arg1、arg2.。。。)或者param1(param2、param3.。。。)
ResultMap单表使用方式
如果在实体类中,属性的名称和数据库是对应的,那么MyBatis可以帮助我们自动映射,但是如果属性名和数据库中的不同,我们就得自己进行配置了。
<!--id是自己取得名字,type是类名-->
<resultMap id="userMap" type="user">
<!--主键需要使用id标签来映射,其中column是数据库中的列名,property是实体类中的名字-->
<id column="username" property="name"/>
<!--其余的使用result来映射-->
<result column="password" property="pass"/>
</resultMap>
<!--在需要映射的地方需要配置resultMap属性-->
<select id="selectPages" resultType="User" resultMap="userMap">
select * from users limit #{param1},#{param2}
</select>
多表查询
使用resultMap实现关联单个对象(N+1方式)
所谓N+1次查询实际就是通过查询数据库获得一张表的详细信息,然后在通过这张表里的信息获取另一张表的信息。在没有使用MyBatis的时候这些装配步骤需要我们在service中通过代码来实现。而现在我们可以通过配置在MyBatis的mapper.xml中来完成这些步骤。
实体类设计:
public class Student {
private int id; // id
private String name; //姓名
private int age; //年龄
private int tid; //外键
private Teacher teacher; //老师
}
teacherMapper:
<select id="selById" resultType="teacher" parameterType="int">
<!--根据id查询某一个老师-->
select * from teacher where id=#{0}
</select>
studentMapper:
<resultMap type="student" id="stuMap">
<result column="tid" property="tid"/>
<!-- 如果关联一个对象 -->
<!--其中tid是student中的一个变量,同时也是teacherMapper中的查询参数-->
<association property="teacher" select="com.bjsxt.mapper.TeacherMapper.selById"
column="tid">
</association>
</resultMap>
<select id="selAll" resultMap="stuMap">
select * from student
</select>
注意:
使用 N+1 方式时如果列名和属性名相同可以不配置,使用 Auto mapping 特性。但是 mybatis 默认只会给列专配一次,也就是说在使用某一列做参数时这一列必须配置标签。例如上面的tid,别的都可以不配,但是tid必须要进行配置。
使用resultMap实现关联单个对象(联合查询方式)
在mysql数据库中,连接查询有很多种,但是比较常用的用三种,一种是内连接(等值连接),一种是左外连接,还有一种是右外连接。外连接和内连接的语法相似,但是内连接只有两个相等才会去查询,然而外连接如果找不到相等的值,依然会查询,但是查不到的部分为null。
studentMapper:
<?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的值不要忘记写-->
<mapper namespace="com.zw.mysql.mapper.StudentMapper">
<resultMap id="selectMap" type="Student">
<id column="sid" property="sid"/>
<result column="stuname" property="stuName"/>
<result column="tid" property="tid"/>
<!--注意,这里的property的值是你在实体类里自己取的名字,而不是类名,javaType对应的是返回值的类型-->
<association property="teacher" javaType="Teacher">
<id column="tid" property="tid"/>
<result column="tname" property="tName"/>
</association>
</resultMap>
<!--resultMap的值是上面resultMap中id属性的值-->
<select id="selectByName" resultMap="selectMap">
SELECT s.sid,s.stuname,s.tid,t.tid,t.tname FROM student s LEFT JOIN teacher t
ON s.tid = t.tid WHERE s.stuname = #{0};
</select>
</mapper>
只要专配一个对象就用这个标签
N+1 方式和联合查询方式对比
-
N+1:需求不确定时。
-
联合查询:需求中确定查询时两个表一定都查询。
-
N+1 名称由来:
举例:学生中有 3 条数据
需求:查询所有学生信息及授课老师信息
需要执行的sql以及N+1分析:
-
查询全部学生信息:
select * from 学生
-
执行 N 遍
select * from 老师 where id=学生的外键
-
使用多条 SQl 命令查询两表数据时,如果希望把需要的数据都查询出来,需要执行 N+1 条 SQl 才能把所有数据库查询出来。
-
缺点:效率低
-
优点:如果有的时候不需要查询学生同时查询老师。只需要执行一个
select * from student
(?) -
适用场景: 有的时候需要查询学生同时查询老师,有的时候只需要查询学生。
-
如何解决 N+1 查询带来的效率低的问题:
- 默认带的前提: 每次都是两个都查询。
- 使用两表联合查询。
-
使用resultMap实现关联集合对象(N+1)
-
在Teacher类中添加List< Student >
-
StudentMapper.xml
<select id="selectByTid" resultType="Student"> select sid,stuname,tid from student where tid = #{0} </select>
-
TeacherMapper.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.zw.mysql.mapper.TeacherMapper"> <resultMap id="selectTeacher" type="Teacher"> <id column="tid" property="tid"/> <result column="tname" property="tName"/> <collection property="list" select="com.zw.mysql.mapper.StudentMapper.selectByTid" column="tid"/> </resultMap> <select id="selectById" resultType="Teacher"> select * from teacher where tid = #{0} </select> <select id="selectAllTeacher" resultMap="selectTeacher"> select * from teacher </select> </mapper>
使用resultMap实现关联集合对象(连接查询)
TeacherMapper.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.zw.mysql.mapper.TeacherMapper">
<resultMap id="selectTeacher" type="Teacher">
<id column="tid" property="tid"/>
<result column="tname" property="tName"/>
<!-- <collection property="list" select="com.zw.mysql.mapper.StudentMapper.selectByTid" column="tid"/>-->
<collection property="list" ofType="Student">
<id column="sid" property="sid"/>
<result column="stuname" property="stuName"/>
<result column="tid" property="tid"/>
</collection>
</resultMap>
<select id="selectById" resultType="Teacher">
select *
from teacher
where tid = #{0}
</select>
<select id="selectAllTeacher" resultMap="selectTeacher">
<!--select * from teacher-->
SELECT s.sid, s.stuname, s.tid, t.tid, t.tname
FROM teacher t LEFT JOIN student s
ON s.tid = t.tid
</select>
</mapper>
使用 Auto Mapping 结合别名实现多表查询
- 只能使用多表联合查询方式。
- 要求:查询出的列别和属性名相同。
<select id="selectByAutoMapping" resultType="Student">
SELECT s.sid, s.stuname, s.tid, t.tid `teacher.tid`, t.tname `teacher.tname`
FROM student s LEFT JOIN teacher t ON s.tid = t.tid
</select>
附: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>
<!--一下配置在使用时位置是有要求的-->
<settings>
<!--是否开启缓存-->
<setting name="cacheEnabled" value="true"/>
<!--配置LOG4J-->
<setting name="logImpl" value="LOG4J "/>
</settings>
<!--为类取别名使用-->
<typeAliases >
<!--上面这种是对具体的某一个类进行简化-->
<typeAlias type="com.yuanKnow.sm.domain.Log" alias="log"/>
<!--对某一个包下的所有的类都进行简化-->
<package name="com.yuanKnow.sm.domain"/>
</typeAliases>
<!--配置环境,可以配置多个,当前使用的是default指定的配置-->
<environments default="mysql">
<environment id="mysql">
<!--事务类型,一般就指定JDBC,另一个没什么用-->
<transactionManager type="JDBC"/>
<!--数据库连接池配置,有三个属性,使用POOLED,不使用UNPOOLED,使用JNDI-->
<dataSource type="POOLED">
</dataSource>
</environment>
</environments>
<!--配置映射关系,告诉mybatis去哪儿找映射文件,这一步用来加载映射文件-->
<mappers>
<!--如果不使用接口绑定技术则使用resource设置所写的xml文件,可以配置多个-->
<!--<mapper resource="com/zw/mybatis/mapper/UserMapper.xml"/>-->
<!--如果使用接口绑定技术,则使用下面两种方式,这就要求我们映射文件路径要和接口的保持一致-->
<!--这一种指定具体的某个接口-->
<mapper class="com.yuanKnow.sm.dao.SelfDao"/>
<!--这一种使用包扫描的方式,mybatis会扫描该包下所有的文件-->
<!--<package name="com.zw.mybatis.mapper"/>-->
</mappers>
</configuration>
使用sql片段
<sql id="select_like">
<if test="items != null">
<if test="items.name != null and items.name != ''">
name like '%${items.name}%'
</if>
</if>
</sql>
<select id="queryItems" parameterType="ItemsQueryAo" resultType="ItemsCustom">
select * from items
<where>
<include refid="select_like"/>
</where>
</select>