Mybatis学习心得
环境:百度配置

回顾:
1. JDBC
2. Mysql
3. java基础
4. Maven
5. Junit

一、Mybits简述:

1.1什么是Mybist?

  • MyBatis 是一款优秀的持久层框架
  • 它支持自定义 SQL、存储过程以及高级映射。
  • MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
  • MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

如何获得Mybatis?

  • Maven
 <dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>x.x.x</version></dependency>
  • Github :
  • 中文文档:https://mybatis.org/mybatis-3/zh/configuration.html#

1.2持久化

数据持久化

  • 持久化就是将程序的数据在持久状态和顺势状态转化的过程
  • 内存:断电即失
  • 数据库(jdbc),io文件等都可以将数据持久化
  • 生活:银行放在前里面,冷藏等

为什么要持久化?

  • 有一些对象,不能让他丢掉!!!
  • 内存太贵了,需要将大部分数据放在外存里面存储

1.3 持久层
我们学过几个层,有Dao层,有Service层,有Controller层,所有的层都有很明显的特点:

  • 层与层之间的界限非常明显,如果Service不去调用Dao层,两个层之间是不会有交集的
  • 持久层是完成持久化工作的代码块,也就是与数据库打交道的地方

1.4 为什么需要Mybatis?

  • 帮助程序员更加方便将数据存到数据库中!
  • 传统的JDBC太复杂

Mybatis的特点:

  • 简单易学
  • 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。
  • sql写在xml里,便于统一管理和优化。sql和代码的分离,提高了可维护性。
  • 提供映射标签,支持对象与数据库的orm字段关系映射 提供对象关系映射标签,支持对象关系组建维护
  • 提供xml标签,支持编写动态sql。

2、第一个Mybatis程序
思路:环境搭建->导入jar包->编写代码->测试代码!

2.1、搭建环境

  • 搭建数据库
CREATE DATABASE `mybatis`;USE `mybatis`;CREATE TABLE `user`(
`id` INT(20) PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL
);INSERT INTO `user` VALUES
(1,'小明','123123'),
(2,'李四','123123'),
(3,'小王','123123')
  • 新建项目
    1、新建一个maven项目
    2、删除src目录
    3、导入maven依赖
 <!--导入依赖--><dependencies><!--mysql依赖--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.25</version></dependency><!--mybatis依赖--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.2</version></dependency><!--juit依赖--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency></dependencies>

2.2创建一个新模块

  • 编写Mybatis的核心配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration代表mybatis核心配置-->
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/><property name="username" value="root"/><property name="password" value="root"/></dataSource></environment></environments>
</configuration>
  • 编写Mybatis工具类
public class MybatisUtils {private static SqlSessionFactory sqlSessionFactory;//使用Mybatis第一步:获取sqlSessionFactorystatic{//资源文件String resource = "mybatis-config.xml";try {//用一个流来读取资源文件InputStream  inputStream = Resources.getResourceAsStream(resource);//给sqlSession工厂对象赋值sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);} catch (IOException e) {e.printStackTrace();}}//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。//SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。public static SqlSession getSqlSession(){return sqlSessionFactory.openSession();}
}

2.3、 编写代码

  • 实体类
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;}@Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + '\'' +", pwd='" + pwd + '\'' +'}';}
}
  • Dao接口
public interface UserDao {List<User> getUserlist();
}
  • 接口实现类,
由原来的UserDaoImpl转为mybatis的UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--命名空间绑定的是要实现的接口-->
<mapper namespace="com.spring.dao.UserDao">
<!--id绑定的是实现的方法,resultYype则绑定哪个类--><select id="getUserlist" resultType="com.spring.pojo.User">select * from mybatis.user</select>
</mapper>

2.4、测试

  • 注意点:要为每一个mapper.xml配置mapper 和设置bulid
  • 测试代码
public class UserMapperTest {@Testpublic void test(){// 第一步:获得sqlSessionSqlSession sqlSession = MybatisUtils.getSqlSession();//方式一:通过getMapperUserDao mapper = sqlSession.getMapper(UserDao.class);List<User> list=mapper.getUserlist();//方式二:通过selectlsitList<User> list1 = sqlSession.selectList("com.spring.dao.UserDao.getUserlist");for (User user:list1)System.out.println(user);sqlSession.close();}
}

3、CURD

  • 1.namespace
    绑定的是某个Dao/Mapper接口!

  • 2、select
    选择查询语句
    - id:就是对应的方法名
    - resulType:Sql语句执行的返回值!
    - paramenterType:参数类型!

     - 编写接口User getUserbyId(int id); - 编写sql<select id="getUserlist" resultType="com.spring.pojo.User">select * from mybatis.user</select>- 编写测试@Testpublic void getUserbyId(){SqlSession sqlSession= MybatisUtils.getSqlSession();UserDao mapper = sqlSession.getMapper(UserDao.class);User user=mapper.getUserbyId(1);System.out.println(user);sqlSession.close();}注意:增加删除修改需要提交事务
    
  • 3、Inset

  • 4、update

  • 5、delete

  • 6、分析错误

    • 标签不要错误
    • resource绑定mapper,需要使用路径!
    • 程序配置文件必须规范
    • NullPointerException,没有注册到资源!
    • 输出的xml文件中存在中文乱码问题!
    • maven资源没有到处问题!
  • 7、万能map

    假设类的参数很多,并且很多都是非空,假如我们只需要修改某个参数,恰好那个修改的方法要new,这个时候就必须把其他的参数也写进去,如果用map,就只需要将修改的参数和id放进一个map,将这个map作为参数传进去即可,避免了new对象的时候有很多非空的参数必须填写的情况!

    //万能Mapint add2(Map<String,Object>map);
    
    <insert id="add2" parameterType="map">insert into mybatis.user(id,pwd) value (#{userid},#{userpwd})
    </insert>
    
    @Testpublic void add2(){SqlSession sqlSession=MybatisUtils.getSqlSession();UserDao mapper = sqlSession.getMapper(UserDao.class);Map<String,Object> map= new HashMap<String,Object>();map.put("userid",5);map.put("userpwd","123123");int number = mapper.add2(map);if (number>0){System.out.println("添加成功");sqlSession.commit();}sqlSession.close();}
    

    Map传递参数,直接在sql中取出key即可! 【parameterType=“map”】
    实体对象传递参数,直接在sql中取出对象的属性即可!【parameterType=“Object”】
    只有一个基本类型参数的情况下,可以直接在sql中取到!
    多个参数用Map,或者注解

  • 8、模糊查询

    //模糊查询List<User> getUserList1(String value);
    
    • 8.1 java代码执行的时候,传递通配符% %
    <select id="getUserList1" parameterType="String" resultType="com.spring.pojo.User">select * from mybatis.user where name like (#{value})</select>
    
    @Testpublic void test11(){SqlSession sqlSession=MybatisUtils.getSqlSession();UserDao mapper = sqlSession.getMapper(UserDao.class);List<User> list=mapper.getUserList1("%小%");for (User user : list) {System.out.println(user);}sqlSession.close();}
    
    • 8.2 在xml的sql中使用通配符
    <select id="getUserList1" parameterType="String" resultType="com.spring.pojo.User">select * from mybatis.user where name like "%"#{value}"%"</select>
    
    @Testpublic void test11(){SqlSession sqlSession=MybatisUtils.getSqlSession();UserDao mapper = sqlSession.getMapper(UserDao.class);List<User> list=mapper.getUserList1("小");for (User user : list) {System.out.println(user);}sqlSession.close();}
    

4、配置解析

  • 4.1 mybatis-config.xml 核心配置文件

  • MyBatis的配置文件包含了会深深影响MyBatis行为的设置和属性信息

     - configuration(配置)      - properties(属性)      - settings(设置)        - typeAliases(类型别名)- typeHandlers(类型处理器)        - objectFactory(对象工厂)         - plugins(插件)- environments(环境配置)       - environment(环境变量)       - transactionManager(事务管理器)- dataSource(数据源)        - databaseIdProvider(数据库厂商标识)         - mappers(映射器)
    
  • 4.2 环境配置
    Mybatis可以适应多种环境
    记住,尽管可以配置多个环境,但是每个SqlSessinoFactory实例只能选择一种环境。
    学会使用配置多套运行环境! 就是根据ID配置
    Mybatis默认的事务管理器是JDBC,连接池:POOLED

  • 4.3 属性(properties)
    我们可以通过properties属性来实现引用配置文件
    这些属性可以在外部进行配置,并可以进行动态替换。
    你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。

    关于数据库资源文件的玩法:

    • 可以直接在mybatis-config.xml中全写入

      <dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/><property name="username" value="root"/><property name="password" value="root"/>
      </dataSource>
      
    • 也可以在resources里面另起一个db.properties文件,然后去mybatis-config.xml中引入

      driver=com.mysql.cj.jdbc.Driver
      url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
      username=root
      password=root
      

      注意:在xml中&才需要加amp; 在properties中不需要

      <properties resource="db.properties">
      </properties>
      <environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${driver}"/><property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/></dataSource></environment>
      </environments>
      

      其中,在properties中也可以写一些字段,然后db.properties不写,但是如果两个都写了相同的字段,优先引用外部配置的db.properties文件中的字段。同时,在外部文件中的字段如果values值是错的化,就算xml中properties中的字段values值是对的也会报错!!!

  • 4.4 别名
    类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写,注意按照顺序写在第三位。

    <typeAliases><typeAlias alias="User" type="com.spring.pojo.User"></typeAlias>
    </typeAliases>
    

    或者写成一个包,然后在那个包的所有的实体类用注解@Alias给别名

    @Alias("User")
    public class User {
        <typeAliases><package name="com.spring.pojo"/></typeAliases>
    

    接口实现类里面的ResultType就可以这样写

       <select id="getUserlist" resultType="User">select * from mybatis.user</select>
    
  • 4.5 设置
    这是Mybatis中极为重要的调整设置,会改变Mybatis的运行

    • cacheEnabled :全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。
    • lazyLoadingEnabled: 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。
    • logImpl: 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。
  • 4.6 映射器 (mappers)
    MapperRegistry:注册绑定我们的Mapper文件:
    方式一:使用相对于类路径的资源引用:

    <mappers><mapper resource="com/spring/dao/UserMapper.xml"></mapper></mappers>
    

    方式二:使用class文件绑定注册

    <mappers><mapper class="com.spring.dao.UserMapper"></mapper>
    </mappers>
    

    注意:使用第二种,接口和实现类必须放在同一个包下,且前缀要同名!!

    方式三:使用扫描包

    <mappers><package name="com.spring.dao"/>
    </mappers>
    

    注意点跟第二种方式一样!!!

  • 4.7 生命周期和作用域
    生命周期、作用域都是至关重要的,一位内错误的使用会导致非常严重的并发问题!

    SqlSessionFactoryBuilder:

    • 一旦创建了SqlSessionFactoryBuilder,就不再需要它了!
    • 局部变量

    SqlSessionFactory:

    • 其实就可以想象是JDBC中的数据库连接池
    • 一旦创建了就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例,不然会造成资源的浪费
    • 因此SqlSessinoFactory的最佳作用域应该是应用作用域
    • 最简单的就是使用单例模式或者静态单例模式

    SqlSession:

    • 可以比喻成连接到连接池的一个请求

    • SqlSession的实例线程不安全,所以不能被共享,作用域应该放在请求或者某个方法里面

    • 请求完之后需要关闭!

      每个Mapper就是一个业务

5、解决属性名和字段名不一致的问题

 @Alias("User")public class User {private int id;private String name;private String password;}
  • 测试问题:
User{id=1, name='sss', password='null'}

解决方法:

  • 1、起别名:
 <select id="getUserbyId" resultType="User" parameterType="int">select id,name,pwd as password from mybatis.user where id = #{id}</select>
  • 2、resultMap
    结果集映射,通过在接口实现类xml中设置resultMap,将数据库中与dao中实体类不一样的字段映射
<!--命名空间绑定的是要实现的接口-->
<mapper namespace="com.spring.dao.UserMapper">
<!--id绑定的是实现的方法,resultYype则绑定哪个类--><!-- type对应要映射的哪个类--><resultMap id="Usermap" type="User"><result column="pwd" property="password"></result></resultMap><select id="getUserbyId" resultMap="Usermap">select *  from mybatis.user where id = #{id}</select>
</mapper>

6 日志工厂

 - SLF4J - LOG4J  掌握- LOG4J2- JDK_LOGGING - COMMONS_LOGGING - STDOUT_LOGGING 掌握- NO_LOGGING

在Mybatis具体使用哪一个日志实现,在核心配置文件中设定!
STDOUT_LOGGING标准日志输出

Created connection 1168420930.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@45a4b042]
==>  Preparing: select * from mybatis.user where id = ?
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd
<==        Row: 1, sss, 123123
<==      Total: 1
User{id=1, name='sss', password='123123'}
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@45a4b042]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@45a4b042]
Returned connection 1168420930 to pool.

LOG4J 日志输出
LOG4J 是什么?

  • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等;

  • 我们也可以控制每一条日志的输出格式;

  • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。

  • 可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。

    1、必须先导入jar包

    <dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version>
    </dependency>
    

    2、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/kuang.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
    

    3、在核心配置文件设置log4j

        <settings><setting name="logImpl" value="LOG4J"/></settings>
    

    简单使用:

    • 1、在使用log4j的类中,导入包import org.apache.log4j.Logger;

    • 2、日志对象,参数为当前类的class

      static Logger logger= Logger.getLogger(UserMapperTest.class);
      
    • 3、日志级别:

      logger.info("sdf");
      logger.debug("sdfs");
      logger.error("ssss");
      

7、分页

7.1 使用limit分页

  • 接口:

     List<User> limitlist(HashMap<String,Integer>map);
    
  • 实现:
    <select id="limitlist" resultMap="Usermap" parameterType="map">select * from mybatis.user limit #{start},#{pagesize};
    </select>
    
  • 测试:
    @Test
    public void test1(){SqlSession sqlSession=MybatisUtils.getSqlSession();UserMapper mapper=sqlSession.getMapper(UserMapper.class);HashMap<String,Integer> map = new HashMap<String,Integer>();map.put("start",0);map.put("pagesize",2);List<User> list=mapper.limitlist(map);for (User user : list) {System.out.println(user);}sqlSession.close();
    }
    

7.2、RowBounds分页(没有sql快)
直接跳过,需要时再来look

8、使用注解开发
8.1、面向接口编程

  • 大家之前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程

  • 根本原因:解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的准则,使得开发变得容易,规范性更好!

  • 在一个面向对象的系统中,系统的各种功能是有许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;

  • 而各个对象之间的协作关系则称为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之处都是着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是按照这种思想来编程的。

    关于接口的理解

    • 接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。
    • 接口的本身反映了系统设计人员对系统的抽象理解。
    • 接口应有两类:
      • 第一类是对一个个体的抽象,它可对应为一个抽象体(abstact class);
      • 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface);
    • 一个个体有可能有多个抽象面。抽象体和抽象面是有区别的

    三个面向区别

    • 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性和方法
    • 面向过程是指,我们考虑问题时,以流程(事务的过程)为单位,考虑它的实现;
    • 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题,更多的体现就是对系统整体的架构

8.2、使用注解开发
不再需要接口实现的xml文件,直接使用java的注解,在括号里面写sql语句,然后去核心配置文件里面写一个mapper

public interface UserMapper {@Select("select * from user")List<User> getUserlist();}

注意:无论是使用xml配置还是java注解实现sql语句,都必须配置mapper

<mappers><mapper class="com.spring.dao.UserMapper"></mapper>
</mappers>

本质:反射机制!
底层:动态代理!

Mybatis详细的执行流程

8.3 CRUD
我们可以在工具嘞创建的时候实现自动提交事务

public static SqlSession getSqlSession(){return sqlSessionFactory.openSession(true);}

增删改查大同小异
接口:

//如果有多个参数必须有@Param("id")包起来;//并且底层在查的时候还是根据@Param("id")里面的值,尽量跟参数写一致@Select("select * from user")List<User> getUserlist();@Select("select * from user where id=#{id}")User getUser(@Param("id") int id);@Insert("insert into user(id,name,pwd) values(#{id},#{name},#{pwd})")int add(User user);@Delete("delete from user where id=#{id}")int delete(int id);@Update("update user set name=#{name},pwd=#{pwd} where id=#{id}")int update(User user);

测试

public class Mytest {@Testpublic void getUserlist(){SqlSession sqlSession= MybatisUtils.getSqlSession();UserMapper mapper=sqlSession.getMapper(UserMapper.class);List<User> list=mapper.getUserlist();for (User user : list) {System.out.println(user);}}@Testpublic void getUserbyId(){SqlSession sqlSession= MybatisUtils.getSqlSession();UserMapper mapper=sqlSession.getMapper(UserMapper.class);User user=mapper.getUser(2);System.out.println(user);sqlSession.close();}@Testpublic void add(){SqlSession sqlSession= MybatisUtils.getSqlSession();UserMapper mapper=sqlSession.getMapper(UserMapper.class);int number=mapper.add(new User(7,"ssss","123123"));if ((number>0))System.out.println("增加成功");sqlSession.close();}@Testpublic void delete(){SqlSession sqlSession= MybatisUtils.getSqlSession();UserMapper mapper=sqlSession.getMapper(UserMapper.class);int number=mapper.delete(7);if ((number>0))System.out.println("删除成功");sqlSession.close();}@Testpublic void update(){SqlSession sqlSession= MybatisUtils.getSqlSession();UserMapper mapper=sqlSession.getMapper(UserMapper.class);int number=mapper.update(new User(1,"111","123123"));if ((number>0))System.out.println("修改成功");sqlSession.close();}
}

简单的SQL语句可以用java注解编写,复杂的还是要用接口实现类xml配置文件实现

关于@Param()注解

 - 基本类型的参数或者String类型,需要加上- 引用类型不需要加- 如果只有一个基本类型的话,可以忽略,但是建议大家都加上!- 我们在Sql重引用的就是我们这里的@Param()设定的属性名!

$ 和 #的区别:

#{}

  • 预编译处理
  • 会替换成?
  • 有效的防治SQL注入

${}

  • 字符串替换
  • 调用PreparedStatement的set方法进行赋值
  • 会替换成变量的值 有效的防治SQL注入,提高代码的安全性

9、Lombok

 - Project Lombok is a java library that automatically plugs into youreditor and build tools, spicing up your java. - Never write anothergetter or equals method again, with one annotationyour class has a fully featured builder, Automate your loggingvariables, and much more.
  • java library
  • plugs
  • build tools
  • with one annotation your class

使用步骤:

  1. 在IDEA中安装Lombok插件!
  2. 在项目中导入Lombok的jar包!
    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.20</version></dependency>
    
  3. @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:无参构造,get,set,tostring,hashcode,equals
    @AllAtgsConstructor 有参构造
    @NoArgsConstructor 无参构造
    @EqualsAndHashCode

     @Alias("User")@Data@AllArgsConstructor@NoArgsConstructorpublic class User {private int id;private String name;private String pwd;
    }
    

10、多对一处理
多个学生对一个老师

测试环境搭建

  • 1、导入lombok

     <dependencies><!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.20</version></dependency></dependencies>
    
  • 2、新建实体类 Teacher Student

    @Alias("Student")
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Student {private int id;private String name;private Teacher teacher;
    }@Alias("Teacher")
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Teacher {private int id;private String name;
    }
  • 3、Mapper接口

    public interface StudentMapper {List<Student> getStudentlist();List<Student> getStudentlist2();
    }
  • 4、Mapper.xml文件

    <!--命名空间绑定的是要实现的接口-->
    <mapper namespace="com.spring.dao.StudentMapper"><!--id绑定的是实现的方法,resultYype则绑定哪个类--><select id="getStudentlist2" resultMap="StudentTeacher2">SELECT s.id sid,s.name sname,t.id tid,t.name tnameFROM student s,teacher tWHERE s.`tid`=t.`id`</select><resultMap id="StudentTeacher2" type="Student"><result property="id" column="sid"></result><result property="name" column="sname"></result><association property="teacher" javaType="Teacher"><result property="id" column="tid"></result><result property="name" column="tname"></result></association></resultMap><!--=================================================--><select id="getStudentlist" resultMap="StudentTeacher">select * from mybatis.student</select><!--复杂属性是对象的用association,嵌套子查询--><resultMap id="StudentTeacher" type="Student"><result property="id" column="id"></result><result property="name" column="name"></result><association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association></resultMap><select id="getTeacher" resultType="Teacher">select * from mybatis.teacher where id=#{tid}</select>
    </mapper>
    
  • 5、在核心配置文件中注册绑定我们的mapper接口

    <mappers><package name="com.spring.dao"/>
    </mappers>
    
  • 6、测试

    • 按照嵌套子查询测试

      <!--命名空间绑定的是要实现的接口-->
      <mapper namespace="com.spring.dao.StudentMapper"><!--id绑定的是实现的方法,resultYype则绑定哪个类--><select id="getStudentlist" resultMap="StudentTeacher">select * from mybatis.student</select><!--复杂属性是对象的用association,嵌套子查询--><resultMap id="StudentTeacher" type="Student"><result property="id" column="id"></result><result property="name" column="name"></result><association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association></resultMap><select id="getTeacher" resultType="Teacher">select * from mybatis.teacher where id=#{tid}</select>
      </mapper>
      先把一个学生的信息查出来,然后根据嵌套查询的getTeacher将学生对象的teacher属性查出来。
      
    • 按照结果嵌套联表查询
      <!--命名空间绑定的是要实现的接口-->
      <mapper namespace="com.spring.dao.StudentMapper"><!--id绑定的是实现的方法,resultYype则绑定哪个类--><select id="getStudentlist2" resultMap="StudentTeacher2">SELECT s.id sid,s.name sname,t.id tid,t.name tnameFROM student s,teacher tWHERE s.`tid`=t.`id`</select><resultMap id="StudentTeacher2" type="Student"><result property="id" column="sid"></result><result property="name" column="sname"></result><association property="teacher" javaType="Teacher"><result property="id" column="tid"></result><result property="name" column="tname"></result></association></resultMap>
      </mapper>
      先根据学生tid和教师id相同的查出一条信息,然后学生的信息id=id,name=name;
      但是teacher则要转换成teacher对象,根据查到的结果tid和tname用resultmap的assocaition转换。
      

11、一对多处理

  • 环境搭建

  • 实体类

    @Alias("Student")
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Student {private int id;private String name;private int tid;
    }
    
    @Alias("Teacher")
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Teacher {private int id;private String name;private List<Student> students;
    }
    
  • 接口类

    public interface TeacherMapper {List<Teacher> getTeacherlist();
    List<Teacher> getTeacherlist2();
    }
    
  • 实现类

    • 按照结果集查询

         <select id="getTeacherlist" resultMap="TeacherStudent">SELECT s.id sid,s.name sname,t.id tid,t.name tnameFROM student s,teacher tWHERE s.`tid`=t.`id`</select><resultMap id="TeacherStudent" type="Teacher"><result property="id" column="tid"></result><result property="name" column="tname"></result><collection property="students" ofType="Student"><result property="id" column="sid"></result><result property="name" column="sname"></result><result property="tid" column="tid"></result></collection></resultMap>
      
    • 按照嵌套子查询
          <select id="getTeacherlist2" resultMap="TeacherStudent2">select * from mybatis.teacher;</select><resultMap id="TeacherStudent2" type="Teacher"><result property="id" column="id"></result><result property="name" column="name"></result><collection property="students" column="id" ofType="Student" select="getStudents"></collection></resultMap><select id="getStudents" resultType="Student">select * from mybatis.student where tid=#{id}</select>
      
  • 小结:

    • 1、关联 assoication(多对一)
    • 2、集合 collection(一对多)
    • 3、javaType 用来指定实体类中属性是引用类型的
    • 4、offType 用来指定实体类中属性是集合的
    • 面试高频:Mysql引擎,InnoDB底层原理、索引、索引优化

12、动态Sql
什么叫动态Sql:就是指根据不同的条件生成不同的sql语句

 利用动态Sql这一特性可以彻底摆脱这种痛苦动态Sql元素和JSTL或者基于XML的文本处理器类似。在Mybatis之前的版中,有很多元素需要花时间了解。Mybatis3大大精简了元素种类,现在只需要学习原来一半的元素即可。Mybatis采用功能强大的基于OGNL的表达式来淘汰其他大部分元素。ifchoose(when,otherwise)trim(where,set)foreach
  • 搭建环境:

    CREATE TABLE `blog`(
    `id` VARCHAR(50) NOT NULL COMMENT '博客id',
    `title` VARCHAR(100) NOT NULL COMMENT '博客标题',
    `author` VARCHAR(30) NOT NULL COMMENT '博客作者',
    `create_time` DATETIME NOT NULL COMMENT '创建时间',
    `views` INT(30) NOT NULL COMMENT '浏览量'
    )ENGINE=INNODB DEFAULT CHARSET=utf8
    
  • 创建一个基础工程

    • 导包
    • 配置文件
    • 实体类
    @Alias("Blog")
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Blog {private String id;private String title;private String author;private Date createTime;private int views;
    }
    
    • mapper接口和mapper.xml
    public interface BlogMapper {int add(Blog blog);List<Blog> queryBolgIf(Map<String,Object> map);List<Blog> queryBolgChoose(Map<String,Object> map);int update(Map<String,Object> map);
    }
    

    mapper.xml
    IF

    <select id="queryBolgIf" 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>
    

    choose

    <select id="queryBolgChoose" parameterType="map" resultType="Blog">select * from blog<where><choose><when test="title!=NULL"> title=#{title}</when><when test="author!=NULL">and author=#{author}</when><otherwise>and views=#{views}</otherwise></choose></where>
    </select>
    

    set

    <update id="update" parameterType="map">update blog<set><if test="title != null">title=#{title},</if><if test="author != null">author=#{author},</if><if test="createTime != null">createTime=#{createTime},</if><if test="views != null">views=#{views}</if></set><!--记住,位置要放好-->where id=#{id}
    </update>
    

    Sql拼接
    最好基于单表查询,最好没有Where

    <sql id="title-author"><where><if test="title!=NULL">title=#{title}</if><if test="author!=NULL">and author=#{author}</if></where>
    </sql><select id="queryBolgIf" parameterType="map" resultType="Blog">select * from blog<include refid="title-author"></include>
    </select>
    

    foreach

    <select id="queryBlogForeach" parameterType="map" resultType="Blog">select * from mybatis.blog where id in<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
    </select>
    

    **总结:**动态Sql就是在拼接SQL语句。我们只要保证Sql的正确性,按照Sql的格式去排列组合即可。

13、缓存

  • 13.1、简介

    • 查询:就是将查询到的数据暂存在一个内存中,当我们再次查询相同的数据是,直接走缓存,就不用走数据库了!
    • 什么是缓存?
      1. 存在内存中的临时数据
      2. 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从硬盘上查询,可以直接从缓存中读取,提高查询效率!
      3. 减少与数据库的交互次数,降低系统开销,提高系统效率!
    • 什么样的数据能使用缓存?
      经常查询并且不经常修改的数据
  • 13.2、Mybatis缓存
    • Mybatis包含一个非常强大的查询缓存特性,它可以非常方便的定制和配置缓存。缓存可以提高查询效率
    • Mybatis系统中默认定义了两级缓存:一级缓存和二级缓存
      • 默认情况下,只有一级缓存开启。(SqlSession)
      • 二级缓存需要手动开启和配置,它是基于namespace级别的缓存
      • 为了提高拓展性,Mybatis定义了缓存接口Cache。我们可以通过事先Cache接口来自定义二级缓存
  • 13.3、一级缓存
    • 一级缓存也叫本地缓存:

    • 与数据同义词会话期间查询的数据,直接从缓存中拿,没必要再去数据库查询

    • 测试步骤:

      • 开启日志;
      • 测试在一个SqlSession查询两次记录
      • 查看日志输出
         @Testpublic void test1(){SqlSession sqlSession=MybatisUtils.getSqlSession();SqlSession sqlSession2=MybatisUtils.getSqlSession();UserMapper mapper=sqlSession.getMapper(UserMapper.class);User user=mapper.getUser(1);User user1=mapper.getUser(1);System.out.println(user);System.out.println(user1);System.out.println(user==user1);sqlSession.close();}
        
    • 缓存失效的情况:
      - 查询记录不相同
      - 增加删除修改可能会修改原来的数据,所以缓存失效
      - 手动清除缓存 sqlSeesion.clearCashe();

    • 小结:默认开启,只在一次连接对象中有效,关闭时清除缓存

  • 13.4、二级缓存
    • 二级缓存也叫全局缓存,一级缓存的作用域太低了,所以诞生了二级缓存

    • 基于namespace级别的缓存,一个命名空间,对应一个二级缓存;

    • 工作机制

      • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
      • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存的数据被保存到二级缓存中;
      • 新的会话查询信息,就可以从二级缓存中获取内容;
      • 不同的sqlsession查出的数据会放在自己对应的mapper中;
    • 步骤:

      • 开启全局缓存

        <setting name="cacheEnabled" value="true"/>
        
      • 在mapper.xml中开启

        <!--命名空间绑定的是要实现的接口-->
        <mapper namespace="com.spring.dao.UserMapper"><!--开启二级缓存,先进先出,60秒间隔刷新,存512个,只读--><cacheeviction="FIFO"flushInterval="60000"size="512"readOnly="true"/><select id="getUser" resultType="User" parameterType="int">select * from user where id=#{id}</select>
        </mapper>
        
      • 测试

        @Testpublic void test1(){SqlSession sqlSession=MybatisUtils.getSqlSession();UserMapper mapper=sqlSession.getMapper(UserMapper.class);User user=mapper.getUser(1);System.out.println(user);sqlSession.close();SqlSession sqlSession2=MybatisUtils.getSqlSession();UserMapper mapper2=sqlSession2.getMapper(UserMapper.class);User user2=mapper2.getUser(1);System.out.println(user2);System.out.println(user==user2);sqlSession.close();}
        
    • 问题:如果单纯只用,要将实体类实现Serializable,不然会报错

    • 13.6、自定义缓存

Mybatis学习心得相关推荐

  1. pdc-admin 学习心得

    pdc-admin 学习心得 包结构讲解: com.vip.product.admin.apiclient :调用公司公用的API (邮件.图片.中央授权系统.任务调度系统) com.vip.prod ...

  2. SQL模糊查询学习心得

    SQL模糊查询学习心得 在进行数据库查询时,有完整查询和模糊查询之分. 1. 一般模糊查询语句如下: SELECT 字段 FROM 表 WHERE 某字段 Like 条件 其中关于条件,SQL提供了四 ...

  3. 实训小结---Java框架学习心得

    学习小结 为期两个星期的实训结束了,在这两周的时间里,我学到了不少之前没有接触过的知识,这也是我第一次正式接触前端后端的开发.在学习开发的过程中,出现过不少问题,自己能够解决的.自己不能解决的都有,下 ...

  4. 【一周课表 · 中秋献礼9.2折】 第四期 认证考试、java、python、php、移动开发、系统运维、区块链 【分享学习心得得技术图书/定制T恤/购课券/会员券】)

    [一周课表]: [一周课表]是CSDN学院新推出的学习专栏节目,目的在于带领大家能够一起学习一些课程,认真学习的学员会收到CSDN学院发出的奖励小礼品:技术图书/CSDN学院定制T恤. 规则:在下方评 ...

  5. GRASP模式学习心得

    GRASP模式学习心得 文章目录 GRASP模式学习心得 本文分三个层次 一.GRASP-"通用职责分配软件模式" 二.九个模式的概念.提出的问题以及解决方案 三.在实际编程中的应 ...

  6. Java EE学习心得

    –Java EE学习心得   1.    称为编程专家的秘诀是: 思考-----编程--------思考------编程--.. 编程不能一步到位,不能一上来就编,必须先思考如何写,怎样写?然后再编程 ...

  7. Assembly学习心得

    http://blog.csdn.net/etmonitor/ Assembly学习心得 说明: 最近开始准备把学到的.NET知识重新整理一遍,眼过千遍不如手过一遍,所以我准备记下我的学习心得,已备参 ...

  8. 对于mysql存储过程感想_存储过程学习心得

    存储过程学习心得 (2014-12-28 17:28:06) 标签: it 我使用过几次SQL Server,但所有与数据库的交互都是通过应用程序的编码来实现的.我不知到在哪里使用存储过程,也不了解实 ...

  9. 【转】MyBatis学习总结(四)——解决字段名与实体类属性名不相同的冲突

    [转]MyBatis学习总结(四)--解决字段名与实体类属性名不相同的冲突 在平时的开发中,我们表中的字段名和表对应实体类的属性名称不一定都是完全相同的,下面来演示一下这种情况下的如何解决字段名与实体 ...

最新文章

  1. asp.net传递参数
  2. mysql主从同步 sql_mysql主从同步报错;Slave_SQL_Running: No
  3. Linux 配置JAVA_HOME
  4. 【Project3】技术总结
  5. ABAP--使用SLIN事务码进行ABAP程序扩展语法检查,提高程序开发的质量
  6. matlab怎么重新打开新的代码,方程求解程序代码求助-程序代码修改或新的代码...
  7. 支持上传文件的xhEditor for Typecho EX插件
  8. C#开发笔记之05-迭代器中的状态机(State Machine)到底是什么?
  9. python提取文本中的手机号_Python从vcf文件中读取手机号并进行去重操作
  10. python之路 -- 并发编程之线程
  11. 一文学会哈希法解题,助你事半功倍(leetcode哈希表面试高频题目总结)
  12. Solana沦为“宕机链”:TPS修正主义的又一次失败
  13. SpringBoot整合IoTDB
  14. GitLab-Runner 从安装到配置到入门
  15. PAT A1010 Radix (25 分)
  16. 社区发现算法-Community Detection-NormalizeCut/Louvain/NMF/LPA
  17. 『注册中心』Consul微服务注册中心的使用及相关集群搭建
  18. Computing Trajectory Similarity in Linear Time: A Generic Seed-Guided Neural Metric Learning Appr...
  19. Adobe Premiere Pro 2020 入门教程(三)首选项和快捷键的设置
  20. 转:高层游戏引擎——基于OGRE所实现的高层游戏引擎框架

热门文章

  1. [病毒分析]利用CVE-2012-0158的病毒分析
  2. 关于销量预测方法和采购备货问题
  3. 你知道对白配音文本怎么制作吗?
  4. LaTeX中段落、图片、表格调整空白
  5. webbuilder8开发经验(二)
  6. python中ascii码和字符的转换_python中ASCII码和字符的转换
  7. SAP B1 警报配置---9.3版本之后单独配置
  8. php登录7天免登录,学习猿地-在php中如何实现7天免登录功能
  9. “云”上交通,“翼”路畅行
  10. 计算机学院实验员岗位基本知识,实验室人员岗位职责