笔记55 Mybatis快速入门(六)
相关概念介绍(一)
1.日志
有时候需要打印日志,知道mybatis执行了什么样的SQL语句,以便进行调试。这时,就需要开启日志,而mybatis自身是没有带日志的,使用的都是第三方日志,这里介绍如何开启log4j日志功能。
在src目录下,新建文件log4j.properties,其作用是输出mybatis包下参与Mybatis的类的SQL语句输出:
- # Global logging configuration
 - log4j.rootLogger=ERROR, stdout
 - # MyBatis logging configuration...
 - log4j.logger.mybatis=TRACE
 - # Console output...
 - log4j.appender.stdout=org.apache.log4j.ConsoleAppender
 - log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
 - log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
 
2.事务管理
在一个事务中,只要有一个操作发生错误,那么其他的操作也无效。在Mysql中,只有当表的类型是INNODB的时候,才支持事务。
3.延迟加载
基于注解方式的一对多来了解延迟加载的配置办法。
<1>测试代码,一种分类对应多个产品。但是当只获取分类,不获取产品名字的时候,通过执行日志的输出可以发现,获取产品的sql语句也执行了。
- package mybatis.annotation;
 - import java.io.IOException;
 - import java.io.InputStream;
 - import java.util.List;
 - import org.apache.ibatis.session.SqlSession;
 - import org.apache.ibatis.session.SqlSessionFactory;
 - import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 - import mybatis.mapper.CategoryMapper;
 - import mybatis.pojo.Category;
 - public class testOneToMany {
 - public static void main(String[] args) throws IOException {
 - // TODO Auto-generated method stub
 - String resource = "mybatis-config.xml";
 - InputStream inputStream = org.apache.ibatis.io.Resources.getResourceAsStream(resource);
 - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 - SqlSession session = sqlSessionFactory.openSession();
 - CategoryMapper categoryMapper = session.getMapper(CategoryMapper.class);
 - listAll(categoryMapper);
 - session.commit();
 - session.close();
 - }
 - private static void listAll(CategoryMapper mapper) {
 - List<Category> categories = mapper.list2();
 - for (Category c : categories) {
 - System.out.println(c.getName());
 - // List<Product> products = c.getProducts();
 - // if (products.size() != 0) {
 - // for (Product product : products) {
 - // System.out.println("\t" + product.getName());
 - // }
 - // }
 - }
 - }
 - }
 
执行结果:

<2>在mybatis-config.xml中添加延迟加载配置。
- <settings>
 - <!-- 打开延迟加载的开关 -->
 - <setting name="lazyLoadingEnabled" value="true"/>
 - <!-- 将积极加载改为消息加载,即按需加载 -->
 - <setting name="aggressiveLazyLoading" value="false"/>
 - </settings>
 
<3>执行相同的操作,可以看到,当只查询category中的数据时,并没有查询product表中的数据。

<4>只有在查询产品的时候,才会看到相应的SQL语句。(把代码中的注释去掉,输出产品名称)

4.分页
<1>增加100条记录
- public static void add(CategoryMapper categoryMapper) {
 - for (int i = 0; i < 100; i++) {
 - Category category = new Category();
 - category.setName("category name " + i);
 - categoryMapper.add(category);
 - }
 - }
 
<2>进行分页查询
①xml方式
在Category.xml下添加如下代码:
- <select id="listByPage" resultType="Category">
 - select * from category
 - <if test="start!=null and count!=null">
 - limit #{start},#{count}
 - </if>
 - </select>
 
②注解方式
在CategoryMapper.java中添加如下代码:
- @Select("select * from category limit #{start},#{count}")
 - public List<Category> listByPage(@Param("start") int start, @Param("count") int count);
 
<3>测试
- package mybatis.annotation;
 - import java.io.IOException;
 - import java.io.InputStream;
 - import java.util.HashMap;
 - import java.util.List;
 - import java.util.Map;
 - import org.apache.ibatis.session.SqlSession;
 - import org.apache.ibatis.session.SqlSessionFactory;
 - import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 - import mybatis.mapper.CategoryMapper;
 - import mybatis.pojo.Category;
 - public class testPaging {
 - public static void main(String[] args) throws IOException {
 - // TODO Auto-generated method stub
 - String resource = "mybatis-config.xml";
 - InputStream inputStream = org.apache.ibatis.io.Resources.getResourceAsStream(resource);
 - SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 - SqlSession session = sqlSessionFactory.openSession();
 - CategoryMapper categoryMapper = session.getMapper(CategoryMapper.class);
 - // add(categoryMapper);
 - // xmlPage(session);
 - annotationPage(categoryMapper);
 - session.commit();
 - session.close();
 - }
 - public static void list(CategoryMapper categoryMapper) {
 - List<Category> categories = categoryMapper.list();
 - for (Category category : categories) {
 - System.out.println(category);
 - }
 - }
 - public static void add(CategoryMapper categoryMapper) {
 - for (int i = 0; i < 100; i++) {
 - Category category = new Category();
 - category.setName("category name " + i);
 - categoryMapper.add(category);
 - }
 - }
 - public static void xmlPage(SqlSession session) {
 - Map<String, Integer> params = new HashMap<String, Integer>();
 - params.put("start", 0);
 - params.put("count", 5);
 - List<Category> categories = session.selectList("listByPageXML", params);
 - for (Category category : categories) {
 - System.out.println(category);
 - }
 - }
 - public static void annotationPage(CategoryMapper categoryMapper) {
 - List<Category> categories = categoryMapper.listByPage(1, 1);
 - for (Category category : categories) {
 - System.out.println(category);
 - }
 - }
 - }
 
5.PageHelper
<1>使用第三方分页工具,先导入jar包:jsqlparser-1.0.jar、pagehelper-5.1.0-beta2.jar
<2>在mybatis-config.xml中配置插件。
- <plugins>
 - <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
 - </plugins>
 
<3>在Category.xml中添加新的查询语句
- <select id="listByPageHelper" resultType="Category">
 - select * from category
 - </select>
 
<4>测试,在testPaging.java中添加新方法
- public static void pageHelper(SqlSession session) {
 - PageHelper.offsetPage(0, 5);
 - List<Category> categories = session.selectList("listByPageHelper");
 - for (Category category : categories) {
 - System.out.println(category);
 - }
 - }
 
笔记55 Mybatis快速入门(六)的更多相关文章
- MyBatis学习笔记(一)——MyBatis快速入门
		
转自孤傲苍狼的博客:http://www.cnblogs.com/xdp-gacl/p/4261895.html 一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优 ...
 - mybatis快速入门(六)
		
前面mybatis的入门程序基本上都写完了,就看大家的灵活运用了,今天来吧前面的整合一下封装一个公共的BaseDao 只需要把前面的改造下然后创建一个BaseDao的接口,其它的继承BaseDao接口 ...
 - 笔记56 Mybatis快速入门(七)
		
相关概念介绍(二) 6.一级缓存 <1>在一个session里查询相同id的数据 package mybatis.annotation; import java.io.IOExceptio ...
 - 笔记50 Mybatis快速入门(一)
		
一.Mybatis简介 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis ...
 - 笔记54 Mybatis快速入门(五)
		
Mybatis中注解的使用 1.XML方式的CRUD 新增加接口CategoryMapper ,并在接口中声明的方法上,加上注解对比配置文件Category.xml,其实就是把SQL语句从XML挪到了 ...
 - 笔记53 Mybatis快速入门(四)
		
动态SQL 1.if 假设需要对Product执行两条sql语句,一个是查询所有,一个是根据名称模糊查询.那么按照现在的方式,必须提供两条sql语句:listProduct和listProductBy ...
 - 笔记52 Mybatis快速入门(三)
		
一.更多查询 1.模糊查询 修改Category.xml,提供listCategoryByName查询语句select * from category where name like concat(' ...
 - 笔记51 Mybatis快速入门(二)
		
Mybatis的CRUD 1.修改配置文件Category.xml,提供CRUD对应的sql语句. <?xml version="1.0" encoding="UT ...
 - MyBatis学习总结(一)——MyBatis快速入门
		
一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBatis可以 ...
 
随机推荐
- mybatis中的命名空间(namespace)的作用
			
mybatis中为每一个映射文件添加一个namespace,这样不同的映射文件中sql语句的id相同也不会有冲突,只要定义在映射文件中的sql语句在该映射文件中id唯一就可以
 - HTML CSS的中英文对照
			
python 大蟒蛇 downloads 下载 install 安装 customize 自定义 path 环境变量:路径 optional 可选的 feature 特性特点 documentatio ...
 - 理解EntityFramework两个核心类型的职责 DbSet和D'bContext
			
DbSet与DbContext是多对一的关系DbSet是实体对象的集合,提供了实现CRUD的相应方法DbContext封装与数据库和数据模型相关的功能,依据数据实体状态创建SQL命令,将数据更改保存到 ...
 - springboot集成redis报错-ClassNotFoundException: org.apache.commons.pool2.impl.GenericObjectPoolConfig
			
当使用Springboot 2.0以上版本集成redis的时候遇到报错信息如下: Application run failed org.springframework.beans.factory.Un ...
 - 2018-2-13-win10-UWP-等级控件
			
title author date CreateTime categories win10 UWP 等级控件 lindexi 2018-2-13 17:23:3 +0800 2018-2-13 17: ...
 - teb教程9
			
通过costmap_converter来跟踪和包含动态障碍物 简介:利用costmap_converter来很容易跟踪动态障碍物 1.costmap_converter中提供了一个插件称之为costm ...
 - compiz隐藏最大化窗口标题栏
			
xfwm换了compiz试试,还行,挺方便.就是这个隐藏最大化窗口的标题栏没有现成的ui设置项,google到如下解决方案: 修改后立即生效. https://planetkris.com/2009/ ...
 - BZOJ-3495  前缀优化建图2-SAT
			
题意:有n个城镇被分成了k个郡,有m条连接城镇的无向边.要求给每个郡选择一个城镇作为首都,满足每条边至少有一个端点是首都. 解法:以前没学过,参考https://blog.csdn.net/linkf ...
 - anyka安凯微电子
			
http://www.anyka.com/ 幼教机
 - 38th 字符串与 列表间的转换
			
字符串与 列表间的转换 如何利用字符串 'Life is short ,I use python'输出 :'python use I, short is Life' s = 'Life is shor ...