1、简介 什么是Mybatis
2、第一个Mybatis程序
2.1 搭建环境
2.2 创建一个模块
2.3 编写代码
3、CURD
namespace
select
Insert
update
Delete
万能Map
模糊查询
4、mybatis-config.xml
核心配置文件标签声明顺序:
属性 properties
设置 Settings
类型别名 typeAliases
其他配置环境配置
environments映射器
mappers
方式一:【推荐使用】
方式二:使用class文件绑定注册
方式三:使用包扫描进行注入作用域和生命周期
5、属性名和字段名不一致的问题resultMap
6、日志日志工厂log4jLog4j简单使用
7、分页
使用Limit分页
RowBounds分页(了解)
pageHelper分页插件
8、使用注解开发面向接口开发使用注解开发关于@Param( )注解#{} 和 ${}
9、Lombok
10、多对一处理
1、sql查询结果,再去嵌套处理
2,联表查询
11、一对多处理
用sql结果注入到集合里
按照查询嵌套处理
resultMap
12、动态SQL
IF标签
SQL片段
foreach
select
insert delete update 所有标签
13、缓存(了解)
13.1 简介
13.2 MyBatis缓存
13.3 一级缓存 / 本地缓存
13.4 二级缓存 / 全局缓存
13.5 缓存原理
1、简介
中文文档:
什么是Mybatis
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
2、第一个Mybatis程序
2.1 搭建环境
1,创建一个普通的maven项目
2,删除src目录 (就可以把此工程当做父工程了,然后创建子工程)
3,导入maven依赖,还有:防止我们资源导出至target.class文件失败的问题
<dependencies> <!--mysqlq驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.12</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.4</version> </dependency> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <!--在build中配置resources,来防止我们资源导出失败的问题(很重要!)--> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <!-- 从工程名底下开始,比如 src--> <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>
如果不在build中配置resources,target。.classes就没有userMapper.xml和其他文件
2.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核心配置文件--> <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/db02? userSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/> <property name="username" value="root"/> <property name="password" value="111"/> </dataSource> </environment> </environments> <mappers> <mapper resource="dao/userMapper.xml"/> </mappers> </configuration>
编写mybatis工具类
//sqlSessionFactory --> sqlSession public class MybatisUtils { static SqlSessionFactory sqlSessionFactory = null; static { try { //使用Mybatis第一步 :获取sqlSessionFactory对象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。 public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession();// 要显示写sqlSession.commit();(增删改采用 查不用) } }
补:
public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(true);// 自动提交 } // 自动提交,不需要显示写SqlSession.commit();
2.3 编写代码
实体类
Dao接口
public interface UserDao { public 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"> <mapper namespace="dao.UserDao"> <select id="getUserList" resultType="pojo.User"> select * from user </select> </mapper>
在mybatis核心配置文件中注册每一个mapper.xml文件
<mappers> <mapper resource="dao/userMapper.xml"/> </mappers>
@Test public void test(){ //1.获取SqlSession对象 SqlSession sqlSession = MybatisUtils.getSqlSession(); //2.执行SQL // 方式一:getMapper UserDao userDao = sqlSession.getMapper(UserDao.class); List<User> userList = userDao.getUserList(); for (User user : userList) { System.out.println(user); } //关闭sqlSession sqlSession.close();
可能会遇到的问题:
配置文件没有注册 绑定接口错误 方法名不对 返回类型不对 Maven导出资源问题
3、CURD
namespace
namespace的resource要和Dao/Mapper接口的包名一致:
<mappers> <mapper resource="dao/userMapper.xml"/> </mappers>
select
id:就是对应的namespace中的方法名;
resultType : Sql语句执行的返回值;
parameterType : 参数类型;
public interface UserMapper { public List<User> getUserList(); public void addUser(User user); }
编写对应的mapper中的sql语句
<insert id="addUser" parameterType="com.kuang.pojo.User"> insert into user (id,name,password) values (#{id}, #{name}, #{password}) </insert>
测试:
@Test public void test2() { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = new User(3,"黑子","666"); mapper.addUser(user); sqlSession.commit(); //增删改一定要提交事务 sqlSession.close(); }
Insert update Delete
<?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="dao.UserDao"> <select id="getUserList" resultType="pojo.User"> select * from user </select> <select id="getUserById" resultType="pojo.User" parameterType="_int"> select * from user where id = #{id} </select> <insert id="insertUser" parameterType="pojo.User"> insert into user (id, name, value) values (#{id}, #{name}, #{value}) </insert> <update id="updateById" parameterType="pojo.User"> update user set name = #{name}, value=#{value} where id = #{id} </update> <delete id="deleteBYId" parameterType="int"> delete from user where id = #{id} </delete> </mapper>package dao; import pojo.User; import java.util.List; public interface UserDao { List<User> getUserList(); User getUserById(int id); int insertUser(User user); int updateById(User user); int deleteBYId(int id); }
万能Map
假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应该考虑使用Map。
不然需要new 对象,对面的属性就是很多,会比较麻烦。
UserMapper接口
public void addUser2(Map<String,Object> map);
UserMapper.xml
<!-- 传递map的key--> <insert id="addUser2" parameterType="map"> insert into user (id,name,password) values (#{userid},#{username},#{userpassword}) </insert>
@Test public void test3(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("userid",4); map.put("username","王虎"); map.put("userpassword",789); mapper.addUser2(map); sqlSession.commit();//提交事务 sqlSession.close(); }
Map传递参数:在sql中取出key即可! eg:【parameter=“map”】
对象传递参数:在sql中取出对象的属性即可! 【parameter=“pojo.User”】
只有一个基本类型参数的情况下:直接在sql中取到
多个参数用Map , 或者注解!
模糊查询
原来的sql:
SELECT * from `user` where name like '22%'
<update id="update" parameterType="pojo.User" flushCache="false"> update user set name = #{name} where id = #{id} </update>
//通配符% %(表示任意) List<User> queryLike(@Param("name") String name);
4、mybatis-config.xml 核心配置文件
标签声明顺序:
properties?, settings?, typeAliases?, typeHandlers?, objectFactory?,
objectWrapperFactory?, reflectorFactory?, plugins?, environments?, databaseIdProvider?, mappers?
mybatis-config.xml
属性 properties
我们可以通过properties属性来实现 引用外面的配置文件
这些属性可以在外部进行配置,并可以进行动态替换。
你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。【db.poperties】
编写一个配置文件
db.properties
driver=com.mysql.jdbc.Driver username=root password=111 url=jdbc:mysql://localhost:3306/db02?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Hongkong
在核心配置文件中引入:写在第一个位置
<!--引用外部配置文件--> <properties resource="db.properties"> <property name="username" value="root"/> <property name="password" value="root"/> </properties>
-
可以直接引入外部文件
-
可以在其中增加一些属性配置
-
如果两个文件有同一个字段,优先使用外部配置文件的
设置 Settings
(日志内容在 6、日志)
(cacheEnabled缓存在最后)
<settings> <!-- <setting name="logImpl" value="STDOUT_LOGGING"/>--> <!-- 显示开启全局缓存 默认也是true--> <setting name="cacheEnabled" value="true"/> </settings>
类型别名 typeAliases
-
类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置.
-
意在降低冗余的全限定类名书写。
<typeAliases> <typeAlias type="pojo.User" alias="User"/> </typeAliases>
<mapper namespace="dao.UserDao"> <select id="getUserList" resultType="User"> select * from user </select>
也可以指定一个包,每一个在包 domain.blog 中的 Java Bean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。首字母大写也行
比如 domain.blog.Author 的别名为 author,;若有注解,则别名为其注解值。
<typeAliases> <package name="com.kuang.pojo"/> </typeAliases>
-
在实体类比较少的时候,使用第一种方式。
-
如果实体类十分多,建议用第二种扫描包的方式。
-
第一种可以DIY别名,第二种不行,如果非要改,需要在实体上增加注解。
@Alias("author") public class Author { }
其他配置
-
typeHandlers(类型处理器)
-
objectFactory(对象工厂)
-
plugins 插件 mybatis-generator-core mybatis-plus 通用mapper eg: <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin> </plugins>
插件:
MyBatis 允许你在映射语句执行过程中的某一点进行拦截调用
通过 MyBatis 提供的强大机制,使用插件是非常简单的,只需实现 Interceptor 接口,并指定想要拦截的方法签名即可。
// ExamplePlugin.java @Intercepts({@Signature( type= Executor.class, method = "update", args = {MappedStatement.class,Object.class})}) public class ExamplePlugin implements Interceptor { private Properties properties = new Properties(); public Object intercept(Invocation invocation) throws Throwable { // implement pre processing if need Object returnObject = invocation.proceed(); // implement post processing if need return returnObject; } public void setProperties(Properties properties) { this.properties = properties; } } <!-- mybatis-config.xml --> <plugins> <plugin interceptor="org.mybatis.example.ExamplePlugin"> <property name="someProperty" value="100"/> </plugin> </plugins>
上面的插件将会拦截在 Executor 实例中所有的 “update” 方法调用,这里的 Executor 是负责执行底层映射语句的内部对象。
环境配置 environments
MyBatis 可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境
environment 元素体中包含了 事务管理 和 连接池的配置。
mappers 元素则包含了一组映射器(mapper),这些映射器的 XML 映射文件包含了 SQL 代码和映射定义信息。
-
MyBatis默认的事务管理器就是JDBC ,还有MANAGED
如果你正在使用 Spring + MyBatis,则没有必要配置事务管理器,因为Spring 模块会使用自带的管理器来覆盖前面的配置。
-
连接池:POOLED
映射器 mappers
每一个Mapper.xml都需要在MyBatis核心配置文件中注册
方式一:【推荐使用】
<mappers> <mapper resource="com/kuang/dao/UserMapper.xml"/> </mappers>
方式二:使用class文件绑定注册
<mappers> <mapper class="com.kuang.dao.UserMapper"/> </mappers>
此注意点:
-
接口和他的Mapper配置文件必须同名
-
接口和他的Mapper配置文件必须在同一个包下
方式三:使用包扫描进行注入
<mappers> <package name="com.kuang.dao"/> </mappers>
此注意点:
-
接口和他的Mapper配置文件必须同名
-
接口和他的Mapper配置文件必须在同一个包下
这些配置会告诉 MyBatis 去哪里找映射文件,剩下的细节就应该是每个 SQL 映射文件了,也就是接下来我们要讨论的。
作用域和生命周期
声明周期和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题。
1,SqlSessionFactoryBuilder:
这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了。 因此 SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)。 你可以重用 SqlSessionFactoryBuilder 来创建多个 SqlSessionFactory 实例,但最好还是不要一直保留着它,以保证所有的 XML 解析资源可以被释放给更重要的事情。
2,SqlSessionFactory:
说白了就可以想象为:数据库连接池 SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建一个实例。 因此SqlSessionFactory的最佳作用域是应用作用域(ApplocationContext)。 最简单的就是使用单例模式或静态单例模式。
3,SqlSession:
使用 MyBatis 的主要 Java 接口就是 SqlSession。你可以通过这个接口来执行命令,获取映射器实例和管理事务。在介绍 SqlSession 接口之前,我们先来了解如何获取一个 SqlSession 实例。SqlSessions 是由 SqlSessionFactory 实例创建的。SqlSessionFactory 对象包含创建 SqlSession 实例的各种方法。而 SqlSessionFactory 本身是由 SqlSessionFactoryBuilder 创建的,它可以从 XML、注解或 Java 配置代码来创建 SqlSessionFactory。 连接到连接池的一个请求 SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。 每次收到 HTTP 请求,就可以打开一个 SqlSession,返回一个响应后,就关闭它
注意:
当 Mybatis 与一些依赖注入框架(如 Spring 或者 Guice)搭配使用时,SqlSession 将被依赖注入框架创建并注入,所以你不需要使用 SqlSessionFactoryBuilder 或者 SqlSessionFactory
代码:
public class Utils { static SqlSessionFactory sqlSessionFactory = null; static { String res = "mybatis-config.xml"; try { InputStream inputStream = Resources.getResourceAsStream(res); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession() { return sqlSessionFactory.openSession(true);// 默认提交 } }
这里的Mapper就是:
5、属性名和字段名不一致的问题
resultMap
映射
id name value id name pas
<resultMap id="UserMap" type="pojo.User"> <result column="value" property="pas"></result> <!-- 这里映射 --> <result column="id" property="id"></result><!-- 两边一样的,可以不写,这里写上了--> <result column="name" property="name"></result> </resultMap> <select id="getUserById" resultMap="UserMap"> select * from user where id = #{id} </select>
6、日志
日志工厂
如果一个数据库操作,出现了异常,我们需要排错,日志就是最好的助手!
曾经:sout、debug
现在:日志工厂
SLF4J LOG4J 【掌握】 LOG4J2 JDK_LOGGING COMMONS_LOGGING STDOUT_LOGGING 【掌握】 NO_LOGGING
写在核心xml文件里:注意顺序,大小写,没有空格细节!!
结果:
log4j
什么是Log4j?
Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件; 我们也可以控制每一条日志的输出格式; 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程; 最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
先导入log4j的包
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
log4j.properties:
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码 log4j.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.file = org.apache.log4j.RollingFileAppender log4j.appender.file.File=./log/rzp.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.sq1.PreparedStatement=DEBUG
配置settings为log4j实现
<settings> <setting name="logImpl" value="LOG4J"/> </settings>
Log4j简单使用
在要使用Log4j的类中,导入包 import org.apache.log4j.Logger;
日志对象,参数为当前类的class对象
Logger logger = Logger.getLogger(UserDaoTest.class); // 日志级别 logger.info("info: 测试log4j"); logger.debug("debug: 测试log4j"); logger.error("error:测试log4j");
7、分页
为什么分页? 减少数据的处理量
使用Limit分页
(推荐)
SELECT * from user limit startIndex,pageSize SELECT * from user limit 3 [0-3)
使用MyBatis实现分页,核心SQL
接口
List<User> getUserByLimit(Map<String,Integer> map);
Mapper.xml
<select id="getUserByLimit" parameterType="map" resultType="User"> select * from user limit #{startIndex},#{pageSize} </select>
测试
@Test public void getUserByLimit(){ SqlSession sqlSession = Utils.getSqlSession(); userMapper mapper = sqlSession.getMapper(userMapper.class); HashMap<String, Integer> map = new HashMap<>(); map.put("startIndex", 0); map.put("pageSize", 3); List<User> userByLimit = mapper.getUserByLimit(map); for (User a : userByLimit) System.out.println(a); sqlSession.close(); }
RowBounds分页(了解)
不再使用SQL实现分页(没试对?????????)
接口
List<User> getUserByRowBounds(); // List<User> getUserByRowBounds(@Param("startIndex") int startIndex,@Param("pageSize") int pageSize); // 都不行
mapper.xml
<select id="getUserByRowBounds"> select * from user limit #{startIndex},#{pageSize} </select>
测试
public void getUserByRowBounds(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); RowBounds rowBounds = new RowBounds(1, 2); //通过Java代码层面实现分页 List<User> userList = sqlSession.selectList("com.kaung.dao.UserMapper.getUserByRowBounds", null, rowBounds); for (User user : userList) { System.out.println(user); } sqlSession.close();
pageHelper分页插件
第一步在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> <!-- 不写这个能编译过去,但是再也没有分页功能,商品展示是展示全部商品! --> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin> </plugins> <!-- 其他配置--> </configuration>
通过 MyBatis 提供的强大机制,使用插件是非常简单的,只需实现 Interceptor 接口,并指定想要拦截的方法签名即可。
下面的插件将会拦截在 Executor 实例中所有的 “query” 方法调用,这里的 Executor 是负责执行底层映射语句的内部对象。
@Intercepts( { @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}), @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}), } ) public class PageInterceptor implements Interceptor { ... }
eg: 小米商城:
只是第一次点击“商品管理”,才会degub,后面点击1,2,3,4分页不会debug。
全部过程:
先进入 PageHelper.startPage(pageNum, pageSize)
debug:
1,
/** * 开始分页 * * @param pageNum 页码 * @param pageSize 每页显示数量 * @param count 是否进行count查询 * @param reasonable 分页合理化,null时用默认配置 * @param pageSizeZero true且pageSize=0时返回全部结果,false时分页,null时用默认配置 */ public static <E> Page<E> startPage(int pageNum, int pageSize, boolean count, Boolean reasonable, Boolean pageSizeZero) { Page<E> page = new Page<E>(pageNum, pageSize, count);// 进入2, page.setReasonable(reasonable);//没事 page.setPageSizeZero(pageSizeZero);// 没事 //当已经执行过orderBy的时候 Page<E> oldPage = getLocalPage(); if (oldPage != null && oldPage.isOrderByOnly()) { // 没进去 page.setOrderBy(oldPage.getOrderBy()); } setLocalPage(page); return page; }
2,
private Page(int pageNum, int pageSize, boolean count, Boolean reasonable) { super(0); if (pageNum == 1 && pageSize == Integer.MAX_VALUE) { // 没进去 //当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页,返回全部结果 pageSizeZero = true; pageSize = 0; } this.pageNum = pageNum; this.pageSize = pageSize; this.count = count;// true calculateStartAndEndRow();// 计算起,止行号 setReasonable(reasonable);// reasonable:false } /** * 计算起 止行号 startRow: */ private void calculateStartAndEndRow() { // 计算:o this.startRow = this.pageNum > 0 ? (this.pageNum - 1) * this.pageSize : 0; //(行号??) 从0开始 // 计算:5 this.endRow = this.startRow + this.pageSize * (this.pageNum > 0 ? 1 : 0); }
3,
/** * 设置 Page 参数 * * @param page */ protected static void setLocalPage(Page page) { LOCAL_PAGE.set(page);// page对象:pageNum:1,pageSize:5.其他全部是初始值 // 进4, }
4,
public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); } // PageHelper.startPage(pageNum, pageSize) debug结束
再进入:
PageInfo<ProductInfo> PageInfo = new PageInfo<>(lists);
debug:
/** * 包装Page对象 * * @param list page结果 * @param navigatePages 页码数量 */ public PageInfo(List<T> list, int navigatePages) { if (list instanceof Page) {// 进去 /* Page{ count=true,pageNum=1,pagesize=5,startRow=0,endRow=5, total=19,pages=4,reasonable=false, pageSizeZero=false }" */ Page page = (Page) list; this.pageNum = page.getPageNum(); this.pageSize = page.getPageSize(); this.pages = page.getPages(); this.list = page; this.size = page.size(); this.total = page.getTotal(); //由于结果是>startRow的,所以实际的需要+1 if (this.size == 0) {// 没进去 this.startRow = 0; this.endRow = 0; } else { this.startRow = page.getStartRow() + 1; // ?????????? //计算实际的endRow(最后一页的时候特殊) this.endRow = this.startRow - 1 + this.size; } } else if (list instanceof Collection) {// 没进去 this.pageNum = 1; this.pageSize = list.size(); this.pages = this.pageSize > 0 ? 1 : 0; this.list = list; this.size = list.size(); this.total = list.size(); this.startRow = 0; this.endRow = list.size() > 0 ? list.size() - 1 : 0; }// if (list instanceof Collection) { this.navigatePages = navigatePages;// 默认8 //计算导航页 calcNavigatepageNums();// 进5, //计算前后页,第一页,最后一页 calcPage();// 进6, //判断页面边界 judgePageBoudary();// 进7, } }
5,
PageInfo //导航页码数 private int navigatePages; //所有导航页号 private int[] navigatepageNums; //导航条上的第一页 private int navigateFirstPage; //导航条上的最后一页 private int navigateLastPage; /** * 计算导航页 */ private void calcNavigatepageNums() { //当总页数小于或等于导航页码数时 if (pages <= navigatePages) { navigatepageNums = new int[pages];// [1,2,3,4] for (int i = 0; i < pages; i++) { navigatepageNums[i] = i + 1; } } else{...} }
6,
/** * 计算前后页,第一页,最后一页 */ private void calcPage() { if (navigatepageNums != null && navigatepageNums.length > 0) { navigateFirstPage = navigatepageNums[0]; // int navigateLastPage = navigatepageNums[navigatepageNums.length - 1]; // int if (pageNum > 1) {// 没进去 prePage = pageNum - 1; } if (pageNum < pages) { nextPage = pageNum + 1;// nextPage = 2 } } }
7,
/** * 判定页面边界 */ // private void judgePageBoudary() { isFirstPage = pageNum == 1;// fasle isLastPage = pageNum == pages || pages == 0;;// fasle hasPreviousPage = pageNum > 1;// fasle hasNextPage = pageNum < pages;// true }
最后:
PageInfo:" pageNum=1,pageSize=5,size=5,startRow=1,endRow=5,total=19,pages=4, list=Page{ count=true,pageNum=1,pageSize=5,startRow=0,endRow=5,total=19, pages=4,reasonable=false,pageSizeZero=false},prePage=0,nextPage=2 isFirstPage=true,isLastPage=false,hasPreviousPage=false,hasNextPage=true navigatePages=8,navigateFirstPage=1,navigateLastPage=4,navigatepageNums=[1,2,3,4] }”
8、使用注解开发
根本原因:解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得 开发变得容易,规范性更好
mybatis原理:
面向接口开发
三个面向区别
面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性和方法; 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现; 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题,更多的体现就是对系统整体的架构;
使用注解开发
简单sql使用
注解在接口上实现
//方法存在多个参数,所有的参数前面必须加上@Param("id")注解 @Select("select * from user where id = #{id1}") List<User> getUserById(@Param("id1") int id); @Insert("insert into user(id,name,value) values (#{id},#{name},#{pas})") int add(User user); @Delete("delete from user where id = #{idd}") int del(@Param("idd") int id);
需要在核心配置文件中绑定接口
<mappers> <mapper class="dao.userMapper"></mapper> </mappers>
本质:反射机制实现
底层:动态代理
关于@Param( )注解
基本类型的参数或者String类型,需要加上; 引用类型不需要加; 如果只有一个基本类型的话,可以忽略,但是建议大家都加上; 我们在SQL中引用的就是我们这里的@Param()中设定的属性名;
#{} 和 ${}
9、Lombok
Lombok项目是一个Java库,它会自动插入编辑器和构建工具中,Lombok提供了一组有用的注释,用来消除Java类中的大量样板代码。仅五个字符(@Data)就可以替换数百行代码从而产生干净,简洁且易于维护的Java类。
使用步骤:
在IDEA中安装Lombok插件
在项目中导入lombok的jar包
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.10</version> </dependency>
在pojo类上加注解
eg: @Getter and @Setter @FieldNameConstants @ToString @EqualsAndHashCode @AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor @Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog @Data @Builder @SuperBuilder @Singular @Delegate @Value @Accessors @Wither @With @SneakyThrows @val
测试
@Data @AllArgsConstructor // 全参构造函数 @NoArgsConstructor @ToString @EqualsAndHashCode public class User { private int id; }
10、多对一处理
-
多个学生,对应一个老师
-
对于学生这边而言,关联…多个学生,关联一个老师【多对一】
-
对于老师而言,集合, 一个老师,有很多学生【一对多】
@Data public class Student { private int id; private String name; private Teacher teacher; }
@Data public class Teacher { private int id; private String name; }
-
对象:association
-
集合:collection
StudentMapper.xml :
1、sql查询结果,再去嵌套处理
<!-- 思路: 1. 查询所有的学生信息 据查询出来的学生的tid寻找特定的老师 (子查询) --> <mapper namespace="dao.StudentMapper"> <resultMap id="STMap" type="pojo.Student"> <result column="id" property="id"/> <result column="name" property="name"/> <collection property="teacher" javaType="pojo.Teacher" column="tid" select="getTeacherById"/> <!--javaType是说teacher字段是Teacher对象 tid是user表的字段--> </resultMap> <select id="getStudentAndTName" resultMap="STMap"> select * from student </select> <select id="getTeacherById" resultType="pojo.Teacher"> select * from teacher where id = #{id} # 一个参数,名字随便写 </select> </mapper>
-
子查询 (xxxx where name in(xxx))
2,联表查询
<resultMap id="ST2" type="pojo.Student"> <result property="id" column="sid"></result> <result property="name" column="sname"></result> <association property="teacher" javaType="pojo.Teacher"> <result property="name" column="tname"/> <!-- Teacher其他字段,beab和db名字一样 就不写了--> <result property="id" column="id"/> </association> </resultMap> <select id="selectSAndT" resultMap="ST2"> select s.id sid, s.name sname, t.name tname from student s, teacher t where s.tid = t.id </select>
-
联表查询 (xxx from teacher t,student t where xxxx)
11、一对多处理
一个老师多个学生;
对于老师而言,就是一对多的关系;
实体类
@Data public class Student { private int id; private String name; private int tid; } @Data public class Teacher { private int id; private String name; List<Student> students; // 放多个
用sql结果注入到集合里
List<Teacher> getTeacherAndStudent(@Param("idd") int id);
<resultMap id="ST" type="pojo.Teacher"> <result property="id" column="tid"/> <result property="name" column="tname"/> <collection property="students" ofType="pojo.Student"> <result property="id" column="id"/> <result property="name" column="name"/> <result property="tid" column="tid"/> </collection> </resultMap> <select id="getTeacherAndStudent" resultMap="ST"> select s.id, s.name, t.id tid, t.name tname from student s, teacher t where s.tid = t.id and s.tid = #{idd} # 一个参数,名字随便写 </select>
按照查询嵌套处理
Teacher getTeacherAndStudent2(@Param("idd") int id);
<!--集合中的泛型用ofType表示--> <resultMap id="ST2" type="pojo.Teacher"> <collection property="students" javaType="ArrayList" ofType="pojo.Student" select="getStudentByTeacherId" column="id"/> <!--teacher表的的id是user表的tid --> <!-- 其他 属性正常 这里不用麻烦声明--> </resultMap> <select id="getTeacherAndStudent2" resultMap="ST2"> select * from teacher where id = #{idd} </select> <select id="getStudentByTeacherId" resultType="pojo.Student"> select * from student where tid = #{tid} # 一个参数,名字随便写 </select>
小结
关联 - association 【多对一】 集合 - collection 【一对多】 javaType & ofType JavaType是方法左边引用的类型,他是什么这里就是什么 ofType是<>泛型中的约束类型
注意点:
保证SQL的可读性,尽量保证通俗易懂 注意一对多和多对一,属性名和字段的问题 如果问题不好排查错误,可以使用日志,建议使用Log4j
resultMap
12、动态SQL
搭建环境
CREATE TABLE `mybatis`.`blog` ( `id` int(10) NOT NULL AUTO_INCREMENT COMMENT '博客id', `title` varchar(30) NOT NULL COMMENT '博客标题', `author` varchar(30) NOT NULL COMMENT '博客作者', `create_time` datetime(0) NOT NULL COMMENT '创建时间', `views` int(30) NOT NULL COMMENT '浏览量', PRIMARY KEY (`id`) )
编写实体类
@Data @AllArgsConstructor @NoArgsConstructor public class Blog { private String id; private String title; private String author; private Date createTime;//数据库:create_time private int views; }
IF标签
<select id="queryIF" parameterType="map" resultType="pojo.Blog"> select * from blog where 1 = 1 <if test="title != null"> title = #{title} </if> <if test="author != null"> and author = #{author} </if> </select>
<configuration> <properties resource="db.properties"/> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> <!-- 这样能够让 private Date createTime和数据库:create_time 对应上!! --> </settings> <!-- 。。--> </configuration>
@Test public void fun() { SqlSession sqlSession = Utils.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); HashMap map = new HashMap(); // map.put("title", "java");// 只有title,sql正确 map.put("author", "乌克兰"); // 错误的sql 有’and‘语法错误 List<Blog> blogs = mapper.queryIF(map); for (Blog blog : blogs) { System.out.println(blog); } sqlSession.close(); }
where
<select id="queryWhere" parameterType="map" resultType="pojo.Blog"> select * from blog <where> <if test="title != null"> title = #{title} </if> <if test="author != null"> and author = #{author} </if> </where> </select>
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
@Test public void fun1() { SqlSession sqlSession = Utils.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); HashMap map = new HashMap(); // map.put("title", "java"); map.put("author", "乌克兰"); // 不管怎么弄都行,sql会把多余的and去掉 List<Blog> blogs = mapper.queryWhere(map); for (Blog blog : blogs) { System.out.println(blog); } sqlSession.close(); }
choose
set
<update id="update" parameterType="map" > update blog <set> <if test="title != null"> title = #{title}, </if> <if test="author != null"> author = #{author}, </if> </set> where id = #{id} </update>
@Test public void fun4() { SqlSession sqlSession = Utils.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); HashMap map = new HashMap(); // map.put("title", "c++"); map.put("author", "乌克兰");// 全注销 sql报错 map.put("id","1"); int update = mapper.update(map); System.out.println(update); sqlSession.close(); }
trim:
如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:
<trim prefix="WHERE" prefixOverrides="AND |OR "> ... </trim>prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。上述例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容。
SQL片段
有的时候,我们可能会将一些功能的部分抽取出来,方便服用!
# 使用SQL标签抽取公共部分可 <sql id="if-title-author"> <if test="title!=null"> title = #{title} </if> <if test="author!=null"> and author = #{author} </if> </sql>
在需要使用的地方使用Include标签引用即可
<!-- 原来样子 --> <select id="queryBlogIF" parameterType="map" resultType="blog"> select * from blog <where> <if test="title!=null"> title = #{title} </if> <if test="author!=null"> and author = #{author} </if> </where> </select> <!-- 现在样子--> <select id="queryBlogIF" parameterType="map" resultType="blog"> select * from blog <where> <include refid="if-title-author"></include> </where> </select>
注意:
-
最好基于单标来定义SQL片段
-
不要存在where标签
-
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以
foreach
原来sql:
SELECT * FROM blog where 1 = 1 and(id = 2 or id = 3)
<select id="queryforEach" parameterType="map" resultType="pojo.Blog"> select * from blog <where> <foreach collection="ids" item="id" open="and (" close=")" separator="or"> id = #{id} </foreach> </where> </select>
@Test public void queryforEach() { SqlSession sqlSession = Utils.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); HashMap map = new HashMap(); ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); map.put("ids", list); // 集合叫:ids List<Blog> blogs = mapper.queryforEach(map); for (Blog blog : blogs) { System.out.println(blog); } sqlSession.close(); }
建议:先在Mysql中写出完整的SQL,再对应的去修改成我们的动态SQL实现通用即可
select insert delete update 所有标签
<select id="selectPerson" parameterType="int" parameterMap="deprecated" resultType="hashmap" resultMap="personResultMap" flushCache="false" useCache="true" timeout="10" fetchSize="256" statementType="PREPARED" resultSetType="FORWARD_ONLY">
属性 | 描述 |
---|---|
id | 在命名空间中唯一的标识符,可以被用来引用这条语句。 |
parameterType | 将会传入这条语句的参数的类全限定名或别名。这个属性是可选的,因为 MyBatis 可以通过类型处理器(TypeHandler)推断出具体传入语句的参数,默认值为未设置(unset)。 |
parameterMap | 用于引用外部 parameterMap 的属性,目前已被废弃。请使用行内参数映射和 parameterType 属性。 |
resultType | 期望从这条语句中返回结果的类全限定名或别名。 注意,如果返回的是集合,那应该设置为集合包含的类型,而不是集合本身的类型。 resultType 和 resultMap 之间只能同时使用一个。 |
resultMap | 对外部 resultMap 的命名引用。结果映射是 MyBatis 最强大的特性,如果你对其理解透彻,许多复杂的映射问题都能迎刃而解。 resultType 和 resultMap 之间只能同时使用一个。 |
flushCache | 将其设置为 true 后,只要语句被调用,都会导致本地缓存和二级缓存被清空,默认值:false。 |
useCache | 将其设置为 true 后,将会导致本条语句的结果被二级缓存缓存起来,默认值:对 select 元素为 true。 |
timeout | 这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数。默认值为未设置(unset)(依赖数据库驱动)。 |
fetchSize | 这是一个给驱动的建议值,尝试让驱动程序每次批量返回的结果行数等于这个设置值。 默认值为未设置(unset)(依赖驱动)。 |
statementType | 可选 STATEMENT,PREPARED 或 CALLABLE。这会让 MyBatis 分别使用 Statement,PreparedStatement 或 CallableStatement,默认值:PREPARED。 |
resultSetType | FORWARD_ONLY,SCROLL_SENSITIVE, SCROLL_INSENSITIVE 或 DEFAULT(等价于 unset) 中的一个,默认值为 unset (依赖数据库驱动)。 |
databaseId | 如果配置了数据库厂商标识(databaseIdProvider),MyBatis 会加载所有不带 databaseId 或匹配当前 databaseId 的语句;如果带和不带的语句都有,则不带的会被忽略。 |
resultOrdered | 这个设置仅针对嵌套结果 select 语句:如果为 true,将会假设包含了嵌套结果集或是分组,当返回一个主结果行时,就不会产生对前面结果集的引用。 这就使得在获取嵌套结果集的时候不至于内存不够用。默认值:false 。 |
resultSets | 这个设置仅适用于多结果集的情况。它将列出语句执行后返回的结果集并赋予每个结果集一个名称,多个名称之间以逗号分隔。 |
<insert id="insertAuthor" parameterType="domain.blog.Author" flushCache="true" statementType="PREPARED" keyProperty="" keyColumn="" useGeneratedKeys="" timeout="20"> <update id="updateAuthor" parameterType="domain.blog.Author" flushCache="true" statementType="PREPARED" timeout="20"> <delete id="deleteAuthor" parameterType="domain.blog.Author" flushCache="true" statementType="PREPARED" timeout="20">
属性 | 描述 |
---|---|
id | 在命名空间中唯一的标识符,可以被用来引用这条语句。 |
parameterType | 将会传入这条语句的参数的类全限定名或别名。这个属性是可选的,因为 MyBatis 可以通过类型处理器(TypeHandler)推断出具体传入语句的参数,默认值为未设置(unset)。 |
parameterMap | 用于引用外部 parameterMap 的属性,目前已被废弃。请使用行内参数映射和 parameterType 属性。 |
flushCache | 将其设置为 true 后,只要语句被调用,都会导致本地缓存和二级缓存被清空,默认值:(对 insert、update 和 delete 语句)true。 |
timeout | 这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数。默认值为未设置(unset)(依赖数据库驱动)。 |
statementType | 可选 STATEMENT,PREPARED 或 CALLABLE。这会让 MyBatis 分别使用 Statement,PreparedStatement 或 CallableStatement,默认值:PREPARED。 |
useGeneratedKeys | (仅适用于 insert 和 update)这会令 MyBatis 使用 JDBC 的 getGeneratedKeys 方法来取出由数据库内部生成的主键(比如:像 MySQL 和 SQL Server 这样的关系型数据库管理系统的自动递增字段),默认值:false。 |
keyProperty | (仅适用于 insert 和 update)指定能够唯一识别对象的属性,MyBatis 会使用 getGeneratedKeys 的返回值或 insert 语句的 selectKey 子元素设置它的值,默认值:未设置(unset )。如果生成列不止一个,可以用逗号分隔多个属性名称。 |
keyColumn | (仅适用于 insert 和 update)设置生成键值在表中的列名,在某些数据库(像 PostgreSQL)中,当主键列不是表中的第一列的时候,是必须设置的。如果生成列不止一个,可以用逗号分隔多个属性名称。 |
databaseId | 如果配置了数据库厂商标识(databaseIdProvider),MyBatis 会加载所有不带 databaseId 或匹配当前 databaseId 的语句;如果带和不带的语句都有,则不带的会被忽略。 |
13、缓存(了解)
13.1 简介
查询 : 连接数据库,耗资源
一次查询的结果,给他暂存一个可以直接取到的地方 --> 内存:缓存
我们再次查询的相同数据的时候,直接走缓存,不走数据库了
-
什么是缓存[Cache]? 存在内存中的临时数据,将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
-
为什么使用缓存? 减少和数据库的交互次数,减少系统开销,提高系统效率
-
什么样的数据可以使用缓存? 经常查询并且不经常改变的数据 【可以使用缓存】
13.2 MyBatis缓存
-
MyBatis包含一个非常强大的查询缓存特性,它可以非常方便的定制和配置缓存,缓存可以极大的提高查询效率。
-
MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
默认情况下,只有一级缓存开启(SqlSession级别的缓存 / 本地缓存)
二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
为了提高可扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来定义二级缓存。
13.3 一级缓存 / 本地缓存
-
一级缓存也叫本地缓存:SqlSession
-
与数据库同一次会话期间查询到的数据会放在本地缓存中
-
以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库
@Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private String value; }
测试在一个Session中查询两次记录
public static void main(String[] args) { SqlSession sqlSession = Utils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.queryById(1); User user1 = mapper.queryById(1); System.out.println(user == user1);// true sqlSession.close(); }
缓存失效的情况:
-
查询不同的东西
-
增删改操作,可能会改变原来的数据,所以必定会刷新缓存
@Test public void fun(){ SqlSession sqlSession = Utils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.queryById(1); mapper.update(new User(2, "a", "a"));// 改 User user1 = mapper.queryById(1); System.out.println(user == user1);//false。 两次从数据库查,两次封装成User对象 sqlSession.close(); }
-
查询不同的Mapper.xml
-
手动清理缓存 sqlSession.clearCache();
@Test public void fun1(){ SqlSession sqlSession = Utils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.queryById(1); sqlSession.clearCache(); // 清理缓存 User user1 = mapper.queryById(1); System.out.println(user == user1);// false sqlSession.close(); }
一级缓存默认开启,一次sqlSession有效
13.4 二级缓存 / 全局缓存
二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存,基于namespace级别的缓存,一个名称空间,对应一个二级缓存
一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
如果会话关闭了,这个会员对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
新的会话查询信息,就可以从二级缓存中获取内容
不同的mapper查询出的数据会放在自己对应的缓存(map)中
只要开启了二级缓存,在同一个Mapper下就有效
所有的数据都会放在一级缓存中
只有当前会话(sqlSession)提交,或者关闭的时候,才会提交到二级缓存中
步骤:
核心配置文件里开启全局缓存
<!--显示的开启全局缓存 默认也是true--> <setting name="cacheEnabled" value="true"/>
在Mapper.xml中使用缓存
<mapper namespace="dao.UserMapper"> <cache flushInterval="60000" size="60" readOnly="true" eviction="FIFO"/> <!-- 开启二级缓存--> <!-- 或者这么写--> <cache/> .... </mapper>
<cache/> 这个简单语句的效果如下:
-
映射语句文件中的所有 select 语句的结果将会被缓存。
-
映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
-
缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
-
缓存不会定时进行刷新(也就是说,没有刷新间隔)。
-
缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
-
缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
@Test public void fun2() { SqlSession sqlSession = Utils.getSqlSession(); SqlSession sqlSession1 = Utils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class); User user = mapper.queryById(1); sqlSession.close(); User user1 = mapper1.queryById(1); sqlSession1.close(); System.out.println(user == user1);// true }
测试 问题:我们需要将实体类序列化,否则就会报错(我没遇到国错误??????)
13.5 缓存原理
注意:
flushCache | 将其设置为 true 后,只要语句被调用,都会导致本地缓存和二级缓存被清空,默认值:false。 |
---|---|
useCache | 将其设置为 true 后,将会导致本条语句的结果被二级缓存缓存起来,默认值:对 select 元素为 true。 |
<select id="getUserById" resultType="user" useCache="true"> select * from user where id = #{id} </select> <update id="update" parameterType="pojo.User" flushCache="false"> update user set name = #{name} where id = #{id} </update>