学习视频链接:B站 遇见狂神说
MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架。
一、简介
三层架构:界面层(User Interface Layer)、业务逻辑层(Business Logic Layer)、数据访问层(Data access Layer)
界面层(表示层,视图层):
主要功能是接受用户的数据,显示请求的处理结果。使用 web 页面和
用户交互,手机 app 也就是表示层的,用户在 app 中操作,业务逻辑在服务器端处理。
业务逻辑层:
接收表示传递过来的数据,检查数据,计算业务逻辑,调用数据访问层获取数据。
数据访问层:
与数据库打交道。主要实现对数据的增、删、改、查。将存储在数据库中的数据提交
给业务层,同时将业务层处理的数据保存到数据库。
三层对应的包:
- 界面层:controller包(servlet)
- 业务逻辑层:service包(XXXService类)
- 数据访问层:dao包(XXXDao类)
三层对应的处理框架:
- 界面层->springmvc(框架),servlet
- 业务逻辑层->spring(框架),service类
- 数据访问层->mybatis(框架),dao类
三层处理请求的交互:
用户->视图层->业务逻辑层->数据访问层->数据库

使用三层架构的优点:
- 结构清晰、耦合度低,各层分工明确。
- 可维护性高,可扩展性高。
- 有利于标椎化。
- 开发人员可以只关注整个结构中某一层的功能实现。
- 有利于各层逻辑的复用。
1-1、什么是Mybatis
Mybatis是一个优秀的基于java的持久层框架,内部封装了jdbc,开发者只需要关注sql语句本身,而不需要处理加载驱动、创建连接、创建statement、关闭连接,资源等繁杂的过程。
- MyBatis 是一款优秀的持久层框架
- 它支持自定义 SQL、存储过程以及高级映射。
- MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
- MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
Mybatis通过xml或注解两种方式将要执行的各种sql语句配置起来,并通过java对象和sql的动态参数进行映射生成最终执行的sql语句,最后由mybatis框架执行sql并将结果映射为java对象并返回。
如何获得Mybatis?
maven仓库
xml<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency>
1-2、持久化
数据持久化
- 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
- 内存:断电即失
- 数据库,io文件持久化。
1-3、持久层
Dao层、Service层、Controller层……
- 完成持久化工作的代码块
- 层界限十分明显。
1-4、为什么需要Mybatis
- 简单易学
- 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
- sql和代码的分离,提高了可维护性。
- 提供映射标签,支持对象与数据库的orm字段关系映射
- 提供对象关系映射标签,支持对象关系组建维护
- 提供xml标签,支持编写动态sql。
二、第一个Mybatis程序
搭建环境–>导入Mybatis–>编写代码–>测试
2-1、搭建环境
搭建数据库
新建项目
新建一个普通的maven项目
删除src
导入maven依赖
xml<!--导入依赖--> <dependencies> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!--mybatis--> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency> </dependencies>
2-2、创建一个模块
编写mybatis的核心配置文件(放在resources目录下,mybatis-config.xml)
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"> <!--指定约束文件,限制,检查当前文件中出现的标签、属性必须符合mybatis的要求。--> <!--configuration核心配置文件--> <configuration> <!--default必须和某个environment的id值一样,是为了告诉mybatis使用那个数据库的连接信息,也就是访问那个数据库--> <environments default="development"> <!--id是一个唯一值,自定义的,表示环境的名称--> <environment id="development"> <!--transactionManager:mybatis的事务类型。type:JDBC(表示使用jdbc中的Connection对象的commit,rollback做事务处理--> <transactionManager type="JDBC"/> <!--dataSource:表示数据源,连接数据库的。type:表示数据源的类型,POOLED表示使用连接池--> <dataSource type="POOLED"> <!--一下name值是固定的,不能自定义--> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> </configuration>
编写mybatis工具类
java//sqlSessionFactory-->sqlSession public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static{ try { //使用Mybatis第一步:获取sqlSessionFactory对象 //定义mybatis主配置文件的名称,从类路径的根开始(target/classes) String resource = "mybatis-config.xml"; //读取配置文件 InputStream inputStream = Resources.getResourceAsStream(resource); //创建SqlSessionFactory对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ /** * openSession()或openSqlSession(false):无参数的,获取非自动提交事务的SqlSession对象 * openSession(true):获取自动提交事务的SqlSession对象 */ return sqlSessionFactory.openSession(); } }
2-3、编写代码
实体类
java//实体类 public class User { private int id; private String name; private String pwd; public User() { } public User(int id, String name, String pwd) { this.id = id; this.name = name; this.pwd = pwd; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", pwd='" + pwd + '\'' + '}'; } }
Dao接口
javapublic interface UserDao { List<User> getUserList(); }
接口实现类(由原来的的UserDaoImpl转变为一个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"> <!--namespace=绑定一个对应的Dao/Mapper接口,要求使用dao/mapper接口的全限定名称--> <mapper namespace="com.lskj.dao.UserDao"> <!--select查询语句--> <select id="getUserList" resultType="com.lskj.pojo.User"> select * from mybatis.user; </select> </mapper>
2-4 测试
junit测试:
@Test
public void test(){
//第一步:获得SQLSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}
SqlSession对象不是线程安全的,需要在方法内部使用。在执行sql语句之前,使用openSession()获取SqlSession对象,在执行完sql语句之后,需要执行SqlSession.close()关闭,这样才能保证它的使用是线程安全的。
遇到的错误
java.lang.ExceptionInInitializerError
…MalformedByteSequenceException: 1 字节的 UTF-8 序列的字节 1 无效。
- 将xml文件中
encoding="UTF-8"
修改为encoding="GBK"
- File->Settings->Editor->File Encodings统一设置编码
- 将xml文件中
配置文件未注册,org.apache.ibatis.binding.BindingException
org.apache.ibatis.binding.BindingException: Type interface com.lskj.dao.UserDao is not known to the MapperRegistry.
核心配置文件中注册mappers
xml<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册--> <mappers> <mapper resource="com/lskj/dao/UserMapper.xml" /> </mappers>
(maven资源导出问题)文件找不到/不存在,The error may exist in com/lskj/dao/UserMapper.xml
pom.xml文件中配置
xml<!--在bulid中配置resources,来防止资源导出失败问题--> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
org.apache.ibatis.exceptions.PersistenceException
SSL=true
修改为SSL=false
空指针异常
没有注册到资源。(例如工具类中
sqlSessionFactory
的作用域)
三、CRUD
3-1、namespace
namespace中的包名要和Dao/mappers接口的包名一致!
3-2、select
选择、查询语句。
- id:就是对应的namespace中的方法名;
- resultType:SQL语句执行的返回值;
- parameterType:参数的数据类型。
编写接口
java//根据ID查询用户 User getUserById(int id);
编写对应的mapper中的sql语句
xml<select id="getUserById" resultType="com.lskj.pojo.User"> select * from mybatis.user where id = #{id}; </select>
测试
java@Test public void getUserById(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); sqlSession.close(); }
3-3、增删改
增删改需要提交事务!
- 编写接口:
//insert一个用户
int addUser(User user);
//修改用户信息
int updateUser(User user);
//删除一个用户
int deleteUser(int id);
编写对应的mapper中的sql语句
xml<!--parameterType不是强制的,可以不用写,mybatis通过反射机制能够发现接口参数的数据类型,一般也不用写--> <insert id="addUser" parameterType="com.lskj.pojo.User"> insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd}); </insert> <update id="updateUser" parameterType="com.lskj.pojo.User"> update mybatis.user set name = #{name},pwd = #{pwd} where id = #{id}; </update> <delete id="deleteUser" parameterType="com.lskj.pojo.User"> delete from mybatis.user where id= #{id}; </delete>
测试
java//增删改需要提交事务 @Test public void addUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int res = mapper.addUser(new User(4, "赵六", "654321")); if (res > 0){ System.out.println("用户信息添加成功!"); } //提交事务 sqlSession.commit(); sqlSession.close(); } @Test public void updateUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int res = mapper.updateUser(new User(4, "王二", "123456")); if (res > 0){ System.out.println("用户数据修改成功!"); } sqlSession.commit(); sqlSession.close(); } @Test public void deleteUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int res = mapper.deleteUser(4); if (res > 0){ System.out.println("用户删除成功!"); } sqlSession.commit(); sqlSession.close(); }
3-4、map的使用
如果实体类或数据库中的表、字段或者参数过多,可考虑使用Map。
编写接口
java//使用map添加一个用户 int addUser2(Map<String,Object> map);
编写对应mapper中的sql语句
xml<!--对象中的属性,可以直接取出来 传递map的key--> <insert id="addUser2" parameterType="map"> insert into mybatis.user (id,name,pwd) values (#{userid},#{username},#{password}); </insert>
测试
java@Test public void addUser2(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Map<String,Object> map = new HashMap<String,Object>(); map.put("userid",5); map.put("username","李好"); map.put("password","123456"); mapper.addUser2(map); sqlSession.commit(); sqlSession.close(); }
Map传递参数直接在SQL中取出key即可。【parameterType=”map”】
对象传递参数,直接在SQL中去对象的属性即可。【parameterType=”Object”】
只有一个基本类型参数的情况下,可以直接在SQL中取到。
多个参数用map,或者注解。
3-5、模糊查询
java代码执行的时候,传递通配符%%
javaList<User> userList = mapper.getUserLike("%李%");
在SQL拼接中使用通配符
xmlselect * from mybatis.user where name like "%"#{value}"%";
编写接口
javaList<User> getUserLike(String value);
编写对应mapper中的sql语句
xml<select id="getUserLike" resultType="com.lskj.pojo.User"> select * from mybatis.user where name like #{value}; </select>
测试
java@Test public void getUserLike(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.getUserLike("%李%"); for (User user:userList ) { System.out.println(user); } sqlSession.close(); }
3-6、@Param
当mapper(dao)接口方法中存在多个参数时,需要通过名称使用参数。在方法形参前面加上@Param("自定义参数名")
,mapper文件使用#{自定义参数名}
。
例如:
List<User> selectUser(@Param("userId") int id,@Param("userName") name);
mapper文件:
<select id="selectUser" resultType="com.lskj.pojo.User">
select * from mybatis.user where id=#{userId} and name=#{userName}
</select>
3-7、多个参数,按位置传值
参数位置从0开始,引用参数语法#{arg位置}
,第一个参数是#{arg0}
,第二个是#{arg1}
。
mybatis3.3版本和之前版本使用#{0},#{1}方式,从mybatis3.4开始使用#{arg0}方式。
例如:
List<User> selectUserByIdOrName(int id,String name);
mapper文件:
<select id="selectUserByIdOrName" resultType="com.lskj.pojo.User">
select * from mybatis.user where id=#{arg0} or name=#{arg1}
</select>
3-8、#和$的区别
#
:占位符,告诉mybaits使用实际的参数值代替。并使用PrepareStatement对象执行sql语句,#{…}代替sql语句的“?”。这样做更安全,更迅速,也是经常使用的。
例如:
<select id="getUserById" resultType="com.lskj.pojo.User">
select * from mybatis.user where id = #{id}
</select>
转换为Mybatis的执行:
String sql = "select * from mybatis.user where id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1,2);
where id = ? 就是where id = #{id}
ps.setInt(1,2),2会替换掉#{id}
$
:字符串替换,告诉mybatis使用$包含的“字符串”替换所在位置。使用Statement把sql语句和${}的内容连接起来。主要用在替换表名,列名,不同列排序等操作。
假设传入的id值为1
select * from mybatis.user where id = #{id}
#的结果:select * from mybatis.user where id = ?
select * from mybatis.user where id = ${id}
$的结果:select * from mybatis.user where id = 1
$替换列名
List<User> selectUser$Order(@Param("colName") String colName);
mapper文件:
<select id="selectUser$Order" resultType="com.lskj.pojo.User">
select * from mybatis.user order by ${colName}
</select>
#和$的区别:
#
使用?
在sql语句中做占位用的,使用PreparedStatement执行sql,效率高#
能够避免sql注入,更安全$
不使用占位符,是字符串连接方式,使用Statement对象执行sql,效率低$
有sql注入的风险,缺乏安全性$
可以替换表名或列名
3-9、resultType
resultType是sql映射文件中定义返回值类型,返回值有基本类型,对象类型,List类型,Map类型等。
执行sql得到ResultSet转换的类型,使用类型的完全限定名或别名。如果返回的是集合,那应该设置为集合包含的类型,而不是集合本身。resultType和resultMap,不能同时使用。
处理方式:
- mybatis执行sql语句,然后mybatis调用类的无参构造方法,创建对象。
- mybatis把ResultSet指定列值赋给同名的属性。
<select id="getUserById" resultType="com.lskj.pojo.User">
select id,name,pwd from user
</select>
对等的jdbc
ResultSet rs = executeQuery("select id,name,pwd from user");
while(rs.next()){
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPwd(rs.getString("pwd"));
}
简单类型
接口方法:
int countUser();
mapper文件:
<select id="countUser" resultType="int">
select count(*) from user
</select>
对象类型
接口方法:
User selectUserById(int id);
UserVo selectUserVoById(int id);
com.lskj.vo.UserVo.java
public class UserVo {
private int id;
private String name;
public User() {
}
public User(int id, String name) {
this.id = id;
this.name = name;
}
//...
}
mapper文件:
<select id="selctUserById" resultType="com.lskj.pojo.User">
select * from user where id=#{id}
</select>
<select id="selectUserVoById" resultType="com.lskj.vo.UserVo">
select id,name from user where id=#{id}
</select>
查询返回Map
- 查询返回map类型值时,列名是map的key,列值是map的value
- 只能最多返回一行记录。
resultType的默认原则是同名的列赋值给同名的属性,使用列别名(Java对象的属性名)
假设有一个实体类MyUser,该实体类中有userid,username,userpwd三个属性。
<select id="selctUserById" resultType="com.lskj.pojo.MyUser">
select id as userid,name as username,pwd as userpwd from user where id=#{id}
</select>
四、配置解析
4-1、核心配置文件
mabatis-config.xml
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。
configuration(配置) properties(属性) settings(设置) typeAliases(类型别名) typeHandlers(类型处理器) objectFactory(对象工厂) plugins(插件) environments(环境配置) environment(环境变量) transactionManager(事务管理器) dataSource(数据源) databaseIdProvider(数据库厂商标识) mappers(映射器)
4-2、环境配置(environments)
MyBatis 可以配置成适应多种环境
尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
Mybatis默认的事务管理器是JDBC,连接池:POOLED。
4-3、属性(properties)
可以通过properties属性来实现引用配置文件。
这些属性可以在外部进行配置,也可以进行动态替换。既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。
在XML中,所有的标签都可以规定其顺序。
1、在resources目录下编写一个配置文件db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=root
2、在mybatis核心配置文件中引入
<!--引入外部配置文件,从类路径跟开始找文件-->
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="root"/>
</properties>
- 可以直接引入外部文件
- 可以在其中增加一些属性配置
- 如果两个文件有同一个字段,优先使用外部配置文件的
3、使用
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
4-4、类型别名(typeAliases)
- 为 Java 类型设置一个缩写名字
- 仅用于 XML 配置,意在降低冗余的全限定类名书写
<!--可以给实体类写别名-->
<typeAliases>
<typeAlias type="com.lskj.pojo.User" alias="User"></typeAlias>
</typeAliases>
也可以指定一个包名,Mybatis会在包名下面搜索需要的Java Bean,例如:
扫描实体类的包,默认别名就是这个类的类名
,首字母小写
。
<typeAliases>
<package name="com.lskj.pojo"/>
</typeAliases>
在实体类比较少的时候,使用第一种方式。
如果实体类十分多,建议使用第二种。
第一种可以DIY别名,第二种不可以,如果需要修改,需要在实体上增加注解。
//实体类
@Alias("user")
public class User {...}
4-5、设置(settings)
settings(设置)是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。
4-6、其它配置
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- mybatis-generator-core
- mybatis-plus
- 通用mapper
4-7、映射器(mappers)
MapperRegistry:注册绑定Mapper文件。
方式一:
<!-- 使用相对于类路径的资源引用 -->
<mappers>
<mapper resource="com/lskj/dao/UserMapper.xml" />
</mappers>
方式二:使用class文件绑定注册
<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
<mapper class="com.lskj.dao.UserMapper"/>
</mappers>
注意点:
- 接口和它的Mapper配置文件必须同名
- 接口和它的Mapper配置文件必须在同一个包下。
方式三:使用扫描包进行注入绑定。
<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
<package name="com.lskj.dao"/>
</mappers>
注意点:
- 接口和它的Mapper配置文件必须同名
- 接口和它的Mapper配置文件必须在同一个包下。
4-8、作用域(Scope)和生命周期

作用域和生命周期是至关重要的,因为错误的使用会导致非常严重的并发问题。
SqlSessionFactoryBuilder:
- 一旦创建了 SqlSessionFactory,就不再需要它
- 局部变量
SqlSessionFactory:
- 可理解为:数据库连接池
- SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
- SqlSessionFactory 的最佳作用域是应用作用域
- 最简单的就是使用单例模式或者静态单例模式
SqlSession:
- 连接到连接池的一个请求
- SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
- 用完之后需要关闭,否则资源被占用

这里面的每一个Mapper,就代表一个具体的业务。
五、解决属性名和字段名不一致的问题
5-1、问题
数据库中的字段:
mybatis.user
字段名 | 类型 |
---|---|
id | int(20) |
name | varchar(30) |
pwd | varchar(30) |
新建一个项目,拷贝之前的,测试实体类字段不一致情况。
public class User {
private int id;
private String name;
private String password;
}
测试发现password='null'
select * from mabatis.user where id = #{id};
//类型处理器
select id,name,pwd from mybatis.user where id = #{id};
解决方法:
起别名
xml<select id="getUserById" resultType="com.lskj.pojo.User"> select id,name,pwd as password from mybatis.user where id = #{id}; </select>
5-2、resultMap
resultMap是Mybatis最强大的元素,它可以将查询到的复杂数据(比如查询到几个表中数据)映射到一个结果集当中。
resultMap和resultType不能一起使用。
结果集映射
id name pwd
id name password
<!--结果集映射-->
<resultMap id="UserMap" type="User">
<!--column数据库中的字段,properties实体类中的属性-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserById" resultMap="UserMap">
select * from mybatis.user where id = #{id};
</select>
resultMap
元素是 MyBatis 中最重要最强大的元素- ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了
ResultMap
最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显示地用到他们。
六、日志
6-1、日志工厂
如果一个数据库操作,出现了异常,需要排错,日志就是最好的助手。
设置名 | 描述 | 有效值 | 默认值 |
---|---|---|---|
logImpl | 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 | SLF4J/LOG4J/LOG4J2/JDK_LOGGING/ COMMONS_LOGGING/ STDOUT_LOGGING/NO_LOGGING |
未设置 |
- SLF4J
- LOG4J
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING
- NO_LOGGING
在Mybatis中具体使用那一个日志实现,在设置中设定。
STDOUT_LOGGING标椎日志输出
在Mybatis核心配置文件中,配置我们的日志。
<!--标椎的日志工厂的实现-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
6-2、LOG4J
可以控制每一条日志的输出格式
通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
通过一个配置文件来灵活地进行配置,而不需要修改应用的代码
先导入log4j的包
xml<!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
log4j.properties
propertieslog4j.rootLogger=DEBUG,console,file #控制台输出的相关设置 log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.Threshold=DEBUG log4j.appender.console.layout = org.apache.log4j.PatternLayout #log4j.appender.console.layout.ConversionPattern=[%c]-%m%n log4j.appender.console.layout.ConversionPattern=%5p [%t] - %m%n #文件输出的相关设置 log4j.appender.file = org.apache.log4j.RollingFileAppender log4j.appender.file.File=./log/lskj.log log4j.appender.file.MaxFileSize=10mb log4j.appender.file.Threshold=DEBUG log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n #日志输出级别 log4j.logger.org.mybatis=DEBUG log4j.logger.java.sql=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
配置log4j为日志实现
xml<settings> <setting name="logImpl" value="LOG4J"/> </settings>
log4j的使用,直接测试运行查询。
简单使用
在要使用Log4j的类中,导入包import org.apache.log4j.Logger;
日志对象,参数为当前类的class
javastatic Logger logger = Logger.getLogger(UserMapperTest.class);
日志级别
javalogger.info("info:进入了testLog4j"); logger.debug("debug:进入了testLog4j"); logger.error("error:进入了testLog4j");
七、分页
- 减少数据的处理量
7-1、使用Limit分页
#语法:select * from user limit startIndex,pageSize;
select * from user limit 4; #[0,n]
使用Mybatis实现分页,核心SQL
接口
java//分页 List<User> getUserByLimit(Map<String,Integer> map);
Mapper.xml
xml<!--分页--> <select id="getUserByLimit" parameterType="map" resultMap="UserMap"> select * from mybatis.user limit #{startIndex},#{pageSize} </select>
测试
java@Test public void getUserByLimit(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); HashMap<String, Integer> map = new HashMap<>(); map.put("startIndex",0); map.put("pageSize",2); List<User> userList = mapper.getUserByLimit(map); for (User user : userList) { System.out.println(user); } sqlSession.close(); }
7-2、RowBounds分页
不再使用SQL实现分页
接口
java//分页 List<User> getUserByRowBounds();
mapper.xml
xml<select id="getUserByRowBounds" resultMap="UserMap"> select * from mybatis.user </select>
测试
java@Test public void getUserByRowBounds(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); //RowBounds实现 RowBounds rowBounds = new RowBounds(1, 2); //通过java代码层面实现分页 List<User> userList = sqlSession.selectList("com.lskj.dao.UserMapper.getUserByRowBounds",null,rowBounds); for (User user : userList) { System.out.println(user); } sqlSession.close(); }
7-3、分页插件
1、导入依赖
<!--PageHelper依赖-->
<dependency>
<grounpId>com.github.pagehelper</grounpId>
<artifactId>pagehelper</artifactId>
<version>5.1.10</version>
</dependency>
2、加入plugin配置。在<environments>
之前加入
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"/
</plugins>
3、PageHelper对象
查询语句之前调用PageHelper.startPage
静态方法。
除了PageHelper.startPage
方法外,还提供了类似用法的PageHelper.offsetPage
方法。
在你需要进行分页的Mybatis查询方法前调用PageHelper.startPage
静态方法即可,紧跟在这个方法后的第一个Mybatis查询方法会被进行分页。
@Test
public void testQuery() throws IOException{
//获取第1页,3条内容
PageHelper.startPage(1,3);
List<User> userList = userMapper.selectUsers();
userList.forEach(user -> System.out.println(user));
}
八、使用注解开发
8-1、面向接口编程
根本原因:解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性更好。
关于接口的理解
- 接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。
- 接口的本身反映了系统设计人员对系统的抽象理解。
- 接口应有两类:
- 第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class)
- 第二类是对一个个体某方面的抽象,即形成一个抽象面(interface)
- 一个体有可能有多个抽象面。抽象体与抽象面是有区别的。
三个面向区别
- 面向对象是指,考虑问题时,以对象为单位,考虑它的属性及方法。
- 面向过程是指,考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的体现。
- 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题,更多的体现就是对系统整体的架构。
8-2、使用注解开发
注解在接口上实现
java@Select("select * from user") List<User> getUsers();
需要在核心配置文件中绑定接口
xml<!--绑定接口--> <mappers> <mapper class="com.lskj.dao.UserMapper"/> </mappers>
测试
java@Test public void test(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.getUsers(); for (User user : userList) { System.out.println(user); } sqlSession.close(); }
本质:反射机制实现
底层:动态代理

Mybatis详细的执行流程

8-3、CRUD
可以在工具类创建的时候实现自动提交事务。
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
编写接口,增加注解
public interface UserMapper {
@Select("select * from user")
List<User> getUsers();
//方法存在多个参数时,所有的参数前面必须加上@Param注解
@Select("select * from user where id = #{id}")
User getUserByID(@Param("id") int id);
@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password})")
int addUser(User user);
@Update("update user set name=#{name},pwd=#{password} where id = #{id}")
int updateUser(User user);
@Delete("delete from user where id = #{uid}")
int deleteUser(@Param("uid") int id);
}
测试类
<!--绑定接口-->
<mappers>
<mapper class="com.lskj.dao.UserMapper"/>
</mappers>
【必须要将接口注册绑定到核心配置文件中】
public class UserMapperTest {
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
//底层使用反射机制
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUsers();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void getUserByID(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
//底层使用反射机制
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User userByID = mapper.getUserByID(1);
System.out.println(userByID);
sqlSession.close();
}
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
//底层使用反射机制
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(7,"七七","111111"));
sqlSession.close();
}
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
//底层使用反射机制
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(7,"七七","123456"));
sqlSession.close();
}
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
//底层使用反射机制
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(6);
sqlSession.close();
}
}
关于@Param()注解
- 基本类型的参数或者String类型,需要加上
- 引用类型不需要加
- 如果只有一个基本类型,可以忽略,但建议加上
- 在SQL中引用的是@Param()中设定的属性名
#{} ${}区别
#{}:采用预编译方式,可以防止SQL注入
${}:采用直接赋值方式,无法阻止SQL注入攻击
九、Lombok
Lombok是一款Java开发插件,使得Java开发者可以通过其定义的一些注解来消除业务工程中冗长和繁琐的代码,尤其对于简单的Java模型对象(POJO)。在开发环境中使用Lombok插件后,Java开发人员可以节省出重复构建,诸如hashCode和equals这样的方法以及各种业务对象模型的accessor和ToString等方法的大量时间。对于这些方法,它能够在编译源代码期间自动帮我们生成这些方法,并没有如反射那样降低程序的性能。
使用步骤:
在IDEA中安装Lombok插件。
在项目中导入lombok的jar包。
xml<dependencies> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency> </dependencies>
在实体类上加注解即可。
java@Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private String password; }
说明:
@Data:无参构造、get、set、toString、hashcode、equals
@AllArgsConstructor
@NoArgsConstructor
@Tostring
@EqualsAndHashcode
@Getter
@Setter
Lombok的优缺点
优点:
1.能通过注解的形式自动生成构造器、getter/setter、equals、hashcode、toString等方法,提高了一定的开发效率
2.让代码变得简洁,不用过多的去关注相应的方法
3.属性做修改时,也简化了维护为这些属性所生成的getter/setter方法等
缺点:
1.不支持多种参数构造器的重载
2.虽然省去了手动创建getter/setter方法的麻烦,但大大降低了源代码的可读性和完整性,降低了阅读源代码的舒适度
十、多对一
SQL:
CREATE TABLE `teacher` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY(`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO`teacher` (`id`,`name`) VALUES (1,'秦老师');
CREATE TABLE `student` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY(`id`),
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `student` (`id`,`name`,`tid`) VALUES ('1','小明','1');
INSERT INTO `student` (`id`,`name`,`tid`) VALUES ('2','小红','1');
INSERT INTO `student` (`id`,`name`,`tid`) VALUES ('3','小张','1');
INSERT INTO `student` (`id`,`name`,`tid`) VALUES ('4','小李','1');
INSERT INTO `student` (`id`,`name`,`tid`) VALUES ('5','小王','1');
10-1、测试环境搭建
- 导入Lombok
- 新建实体类Teacher、Student
- 建立Mapper接口
- 建立Mapper.xml文件
- 在核心配置文件中绑定注册Mapper接口或文件。
- 测试查询是否能够成功。
10-2、按照查询嵌套处理
<!--
1.查询所有的学生信息
2.根据查询出来的学生的tid,寻找对应的老师
-->
<select id="getStudent" resultMap="StudentTeacher">
select * from student;
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--复杂的属性,需要单独处理
对象:association
集合:collection
-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{id}
</select>
10-3、按照结果嵌套处理
<!--按照结果嵌套处理-->
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname
from student s,teacher t
where s.tid = t.id;
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
MySql多对一查询方式:
- 子查询
- 联表查询
十一、一对多
11-1、环境搭建
实体类
@Data
public class Student {
private int id;
private String name;
private int tid;
}
@Data
public class Teacher {
private int id;
private String name;
//一个老师有多个学生
private List<Student> students;
}
11-2、按照结果嵌套处理
<!--按结果嵌套查询-->
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.name tname,t.id tid
from student s,teacher t
where s.tid = t.id and t.id = #{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--复杂的属性,需要单独处理
对象:association
集合:collection
javaType="" 指定属性的类型
集合中的泛型信息:使用ofType获取
-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
11-3、按照查询嵌套处理
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from mybatis.teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from mybatis.student where tid = #{tid}
</select>
关联-association 【多对一】
集合-collection 【一对多】
JavaType & ofType
- JavaType用来指定实体类中属性的类型
- ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型。
注意点:
- 保证SQL的可读性,尽量保证通俗易懂
- 注意一对多和多对一中,属性名和字段的问题
- 如果问题不好排查错误,可以使用日志,建议使用Log4j
十二、动态SQL
动态SQL就是指根据不同的条件生成不同的SQL语句。
12-1、搭建环境
CREATE TABLE `blog` (
`id` VARCHAR(50) NOT NULL COMMENT '博客id',
`title` VARCHAR(100) NOT NULL COMMENT '博客标题',
`author` VARCHAR(30) NOT NULL COMMENT '博客作者',
`ctreate_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8
创建一个基础工程
导包
编写配置文件
编写实体类
java@Data public class Blog { private int id; private String title; private String author; private Date createTime; private int views; }
编写实体类对应的Mapper接口和Mapper.xml文件
12-2、if
<select id="queryBlog" parameterType="map" resultType="blog">
select * from mybatis.blog where 1 = 1
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>
12-3、choose (when, otherwise)
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
12-4、trim (where, set)
<select id="queryBlog" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
where id = #{id}
</update>
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码。
12-5、SQL片段
有的时候,可能会将一些功能的部分抽取出来,方便复用。
使用SQL标签抽取公共的部分
xml<sql id="if-title-author"> <if test="title != null"> and title = #{title} </if> <if test="author != null"> and author = #{author} </if> </sql>
在需要使用的地方使用include标签引用即可
xml<select id="queryBlogIf" parameterType="map" resultType="blog"> select * from mybatis.blog <where> <include refid="if-title-author"></include> </where> </select>
注意事项:
- 最好基于表单来定义SQL片段
- 不要存在where标签
12-6、foreach
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
<!--
collection:表示接口中的方法参数的类型,如果是数组使用array,如果是list集合使用list
item:自定义的,表示数组和集合成员的变量
open:循环开始时的字符
close:循环结束时的字符
separator:集合成员之间的分隔符
-->
<select id="queryBlogForeachOne" resultType="blog">
select * from mybatis.blog id in
<foreach collection="list" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</select>
<select id="queryBlogForeachTwo" resultType="blog">
select * from mybatis.blog id in
<foreach collection="list" item="blog" open="(" close=")" separator=",">
#{blog.id}
</foreach>
</select>
动态SQL就是在拼接SQL语句,只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了。
十三、缓存
13-1、简介
什么是缓存(cache)?
- 存放内存中的临时数据
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用直接从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
为什么使用缓存?
减少和数据库的交互次数,减少系统开销,提高系统效率。
什么样的数据能使用缓存?
经常查询并且不经常改变的数据。
13-2、Mybatis缓存
- Mybatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大地提升查询效率。
- Mybatis系统中默认定义了两级缓存:一级缓存和二级缓存。
- 默认情况下,只有
一级缓存开启
。(SqlSession级别的缓存,也称为本地缓存) - 二级缓存需要手动开启和配置,它是基于namespace级别的缓存。
- 为了提高扩展性,Mybatis定义了缓存接口Cache。可以通过实现Cache接口来自定义二级缓存。
- 默认情况下,只有
13-3、一级缓存
一级缓存也叫本地缓存:
- 与数据库同一次会话期间查询到的数据会放在本地缓存中。
- 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库。
测试步骤:
- 开启日志
- 测试在一个Session中查询两次相同记录
- 查看输出日志
缓存失效的情况:
查询不同的记录;
增删改操作,可能会改变原来的数据,所以必定会刷新缓存;
查询不同的Mapper.xml;
手动清理缓存。
xmlsqlSession.clearCache(); //手动清理缓存
13-4、二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低,所以诞生了二级缓存
- 基于namespace级别的缓存,一个名称空间,对应一个二级缓存
- 工作机制
- 一个会话查询一条数据,这个数据就会放在当前会话的一级缓存中;
- 如果当前会话关闭了,这个会话对应的一级缓存就没了,但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
- 新的会话查询信息,就可以从二级缓存中获取内容;
- 不同的mapper查出的数据会放在自己对应的缓存(map)中。
步骤:
开启全局缓存
xml<!--显示地开启全局缓存--> <setting name="cacheEnabled" value="true"/>
在要使用二级缓存的Mapper中开启
xml<!--在当前mapper.xml中使用二级缓存--> <cache/>
也可以自定义参数
xml<!--在当前mapper.xml中使用二级缓存--> <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
测试
需要将实体类序列化
Cause: java.io.NotSerializableException: com.lskj.pojo.User
- 只要开启了二级缓存,在同一个Mapper下就有效;
- 所有的数据都会先放在一级缓存中;
- 只有当回话提交,或者关闭的时候,才会提交到二级缓存中。
13-5、缓存原理

13-6、自定义缓存-encache
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存。
要在程序中使用encache,先要导包。
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
在mapper中指定使用ehcache缓存实现。
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
ehcache.xml
<?xml version="1.0" encoding="UTF-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<!--
diskStore:为终存路径,ehcache分为内存和磁盘两线,此属性定义然盘的级存位置。参数解释如下:
user.home-用户主日录
user.dir-用户当前工作目录
java.io.tmpdir-就认临时文件路径
-->
<diskStore path="./tmpdir/Tmp_EhCache"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1880"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
Redis数据库来做缓存。