admin管理员组

文章数量:1794759

mybatis学习文档

mybatis学习文档

mybatis-9.28

环境:

  • JDK1.8

  • mysql 8.0.16

  • maven3.6.1

  • IDEA

回顾:

  • JDBC
  • mysql
  • jave基础
  • Maven
  • junit
1.简介 1.1 什么是mybatis

​ mybatis是支持普通SQL查询、存储过程和高级映射的优秀持久层框架。

  • MyBatis 是一款优秀的持久层框架

  • 支持自定义 SQL、存储过程以及高级映射

  • MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作

  • MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录

如何获取mybits:

  • maven仓库

    <!-- mvnrepository/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency>
  • Github:

  • 中文学习文档:mybatis/

1.2 持久化
  • 数据持久化

    • 数据持久化指程序的数据在持久状态与瞬时状态转化的过程

    • 内存:断电即失

    • 数据库(jdbc):io文件持久化

  • 为什么需要持久化

    • 内存太贵了

    • 有些对象不能缺失(如银行的账户和密码)

1.3 持久层

​ dao层、service层、controller层…

  • 完成持久化工作的代码块

  • 界限十分明显

1.4 为什么需要mybatis
  • 简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件易于学习,易于使用,通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
  • 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql基本上可以实现我们不使用数据访问框架可以实现的所有功能,或许更多。
  • 解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
  • 提供映射标签,支持对象与数据库的字段关系映射
  • 提供对象关系映射标签,支持对象关系组建维护
  • 提供xml标签,支持编写动态sql。
2.第一个mybatis程序

步骤

2.1 搭建环境 2.1.1 搭建数据库 create database 'mybatis'; use mybatis; CREATE TABLE user( id int not null PRIMARY KEY, name VARCHAR(20) DEFAULT NULL, psw VARCHAR(20) DEFAULT NULL )ENGINE=INNODB DEFAULT CHARSET=utf8; INSERT INTO USER VALUES(1,'李白','123'),(2,'杜甫','234'),(3,'苏轼','333'); 2.1.2 新建项目
  • 新建一个普通的maven项目

  • 删除一个src目录(父工程)

  • 导入maven依赖

    <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- mvnrepository/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.16</version> </dependency> <!-- mvnrepository/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> </dependencies>
  • 2.2 创建一个模板
    • 编写mybatis的核心配置文件

      <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis//DTD Config 3.0//EN" "mybatis/dtd/mybatis-3-config.dtd"> <configuration> <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> <!--每一个mapper.xml都需要在mybatis核心配置文件中注册--> <mappers> <mapper resource="com/kuang/dao/UserMapper.xml"/> </mappers> </configuration>
    • 编写mybatis工具

      public class MybatisUtil { private static SqlSessionFactory sqlSessionFactory; static { try { //使用mybatis的第一步,获取sqlSessionFactory对象 String resource = "src\\\\main\\\\resources\\\\mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } // 既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。 // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。 public SqlSession getsqlSession(){ return sqlSessionFactory.openSession(); } }
    2.3 编写代码
    • 实体类

      public class User { private int id; private String name; private String psw; public User() { } public User(int id, String name, String psw) { this.id = id; this.name = name; this.psw = psw; } 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 getPsw() { return psw; } public void setPsw(String psw) { this.psw = psw; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\\'' + ", psw='" + psw + '\\'' + '}'; } }
    • Dao接口

      public interface UserDao { List<User> getUserList(); }
    • 接口实现类由原来的UserDaoImpl转变为一个Mapper配置文件

      <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis//DTD Mapper 3.0//EN" "mybatis/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.kuang.dao.UserDao"> <select id="getUserList" resultType="com.kuang.pojo.User"> select * from user </select> </mapper>
    2.4 测试 public class UserDaoTest { @Test public void test(){ //1.获取sqlSession对象 SqlSession sqlSession = MybatisUtil.getsqlSession(); //执行sql UserDao userDao = sqlSession.getMapper(UserDao.class); List<User> userList = userDao.getUserList(); for (User user:userList){ System.out.println(user); } //关闭sqlSession sqlSession.close(); } } 2.5 解决遇到的问题

    可能遇到的问题:

  • 配置文件没有注册

    org.apache.ibatis.binding.BindingException: Type interface com.kuang.dao.UserDao is not known to the MapperRegistry.

    MapperRegistry:映射器注册表

    原因:每一个mapper.xml都需要在mybatis核心配置文件中注册

  • 绑定接口错误

  • 方法名不对

  • 返回类型不对

  • maven导出资源问题

  • 3.CRUD 3.1 namespace、id、resultType、parameterType
    • namespace的值:mapper接口的全限定类名

    • id:mapper接口里面的方法名

    • resultType:sql语句执行的返回值类型

    • parameterType:参数类型

    3.2 select

    选择、查询语句:

  • 编写接口

    //查询--根据用户id User getUserById(int id);
  • 编写对应的mapper中的sql语句

    <select id="getUserById" resultType="com.kuang.pojo.User" parameterType="int"> select * from user where id=#{id} </select>
  • 测试

  • @Test public void getUserById(){ SqlSession sqlSession = MybatisUtil.getsqlSession(); UserDao userDao = sqlSession.getMapper(UserDao.class); User user = userDao.getUserById(1); sqlSession.close(); } 3.3 insert <insert id="addUser" parameterType="com.kuang.pojo.User"> insert into user (id,name,pwd) values (#{id},#{name},#{pwd}) </insert> 3.4 delete <delete id="deleteUserById" parameterType="int"> delete from user where id=#{id} </delete> 3.5 update <update id="updateUserById" parameterType="com.kuang.pojo.User"> update user SET name=#{name},pwd=#{pwd} where id=#{id} </update>

    注意点:

    • 增删改需要提交事务!
    3.6 错误分析
    • 标签不要匹配错
    • resource绑定mapper,需要使用路径!
    • 程序配置文件必须符合规范!
    • 输出的xml文件中存在中文乱码问题!
    • maven资源没有导出问题
    3.7 万能mapper

    UserDao:

    //添加用户--通过map集合 int addUserByMap(Map<String ,Object> map);

    UserMapper.xml

    <insert id="addUserByMap" parameterType="map"> insert into user (id,name,pwd) values (#{userid},#{username},#{password}) </insert>

    测试类:

    @Test public void addUserByMap(){ SqlSession sqlsession = MybatisUtil.getsqlSession(); UserDao mapper = sqlsession.getMapper(UserDao.class); Map<String, Object> map = new HashMap<>(); map.put("userid",6); map.put("username","李四"); map.put("password","222333"); int i = mapper.addUserByMap(map); sqlsessionmit(); sqlsession.close(); }

    map传递参数,直接在sql中取出key 【parameterType=“map”】

    实体类对象传递参数,直接在sql中取出属性 【parameterType=“Object”】

    只有一个基本数据类型,直接在sql中取出

    多个参数时使用Map,或者注释

    3.8 思考题

    模糊查询怎么写?

  • java代码执行的时候,传递通配符%%

    List<User> list =mapper.fuzzleSeltUser("%白%");
  • 在sql拼接的时候使用通配符

    select * from user where name like '%白%'
  • 4.配置解析 1.核心配置文件
  • mybatis-config.xml

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

    configuration(配置) properties(属性) settings(设置) typeAliases(类型别名) typeHandlers(类型处理器) objectFactory(对象工厂) plugins(插件) environments(环境配置) environment(环境变量) transactionManager(事务管理器) dataSource(数据源) databaseIdProvider(数据库厂商标识) mappers(映射器)
  • 2.环境配置(environment)

    注意:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

    学习使用配置多套运行环境

    mybatis默认的事务管理器就是JDBC ,连接池:POOLED

    <transactionManager type="JDBC"/> <dataSource type="POOLED"> </dataSource> 3.属性(properties)

    我们可以通过使用properties属性来实现引用配置文件

    这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置 。[db.properties]

    4.类型别名(typeAliases)

    ​ 注意:它仅用于 XML 配置。比如:UserMapper.xml

    • 类型别名可为 Java 类型设置一个缩写名字。降低冗余的全限定类名

      <!--给实体类取别名--> <typeAliases> <typeAlias type="com.kuang.pojo.User" alias="User"/> </typeAliases>
    • 也可以指定一个包名,MyBatis 会在包名下面搜索需要的 JavaBean:

      每一个在包 中的 JavaBean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名

      <typeAliases> <package name="com.kuang.pojo"/> </typeAliases>
    • 注解的方式

      @Alias("user") public class User { }

    对比:

    如果实体类比较少的话,使用第一种

    如果实体类比较多的话,使用第二种

    第一种可以diy别名,第二种则不可以,如果非要改,需要实体类上加上注解!

    5.设置

    这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HPtqWMsX-1630250334535)(%E4%B8%80%20%E7%AE%80%E4%BB%8B.assets/image-20210818225121449.png)]

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jtTPJunO-1630250334540)(%E4%B8%80%20%E7%AE%80%E4%BB%8B.assets/image-20210818225145141.png)]

    6.其他配置
    • typeHandlers(类型处理器)

    • objectFactory(对象工厂)

    • plugins(插件)

    • mybatis-generator-core

    • mybatis-plus

    • 通用mapper

    7.映射器(mappers)

    告诉 MyBatis 到哪里去找到sql语句

    方法一:使用resource绑定xml(常用)

    <!--每一个mapper.xml都需要在mybatis核心配置文件中注册--> <mappers> <mapper resource="com/kuang/dao/UserMapper.xml"/> </mappers>

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

    <!--每一个mapper.xml都需要在mybatis核心配置文件中注册--> <mappers> <mapper class="com.kuang.dao.UserMapper"/> </mappers>

    方法三:使用扫描包进行绑定

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

    方法二和方法三的注意点:

    • 接口和他的mapper配置文件必须同名
    • 接口和它的mapper配置文件必须在同一个包下

    练习时间:

  • 将数据库配置文件外部引入
  • 实体类别名
  • 保证UserMapper接口和UserMapper.xml一致!并且放在同一个包下
  • 8.生命周期

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-m4oD7y1V-1630250334543)(%E4%B8%80%20%E7%AE%80%E4%BB%8B.assets/image-20210819103146567.png)]

    生命周期和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题

    SqlSessionFactoryBuilder:

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

    SqlSessionFactory:

    • 说白了可以想象为:数据库连接池
    • 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
    • 最佳作用域是应用作用域
    • 最简单的就是使用单例模式或者静态单例模式。

    SqlSession:

    • 连接到连接池的一个请求
    • SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
    • 用完之后赶紧关闭,否则占用资源

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-35UdjopT-1630250334547)(%E4%B8%80%20%E7%AE%80%E4%BB%8B.assets/image-20210819104741208.png)]

    这里的每一个Mapper都代表一个具体业务

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

    数据库的字段名:

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xbraIKJY-1630250334549)(%E4%B8%80%20%E7%AE%80%E4%BB%8B.assets/image-20210819155642300.png)]

    User属性名:

    public class User { private int id; private String name; private String password; }

    根据id查询:

    User{id=1, name=‘李白’, password=‘null’}

    分析原因:

    sql语句- select * from user where id=1 等价 select id,name,pwd from user where id=1

    解决方法:

    • 起别名:

      <select id="getUserById" resultMap="User" parameterType="int"> select id,name,pwd as pasword from user where id=#{id} </select>
    2.resultMap <!--结果集映射--> <resultMap id="UserMap" type="User"> <!--column 数据库中的字段 ,properties 实体类中的属性--> <result column="id" property="id"></result> <result column="name" property="name"></result> <result column="pwd" property="password"></result> </resultMap> <select id="getUserById" resultMap="UserMap"> select * from user where id=#{id} </select>
    • resultMap 元素是 MyBatis 中最重要最强大的元素
    • ResultMap 的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了。
    • ResultMap 最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们。
    6.日志 1.日志工厂

    如果一个数据库出现了异常,我们需要排错。日志就是最好的助手

    曾经:sout、debug

    现在:日志工厂

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NXRPDUEO-1630250334551)(%E4%B8%80%20%E7%AE%80%E4%BB%8B.assets/image-20210819163658648.png)]

    • SLF4J
    • LOG4J【掌握】
    • LOG4J2
    • JDK_LOGGING
    • COMMONS_LOGGING
    • STDOUT_LOGGING【掌握】
    • NO_LOGGING
    2.STDOUT_LOGGING

    STDOUT_LOGGING标准日志输出:(放于mybatis的核心配置文件)

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

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4DRuPgdm-1630250334552)(%E4%B8%80%20%E7%AE%80%E4%BB%8B.assets/image-20210819164436453.png)]

    3.LOG4J

    什么是log4j:

    • Log4j是Apache的一个开放源代码项目,通过使用Log4j,我们可以控制日志信输送的目的地是控制台、文件、GUI组件
    • 我们也可以控制每一条日志的输出格式
    • 通过定义每一条日志信的级别,我们能够更加细致地控制日志的生成过程
    • 最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
    1.使用

    导入log4j的依赖:

    <!-- mvnrepository/artifact/log4j/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/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.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

    加入到核心配置文件中:

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

    测试:

    • 创建日志对象,参数为当前类的class(全局静态变量)
    static Logger logger = Logger.getLogger(UserMapperTest.class); @Test public void testLog4j(){ //日志级别: logger.info("info:进入到testLog4j"); logger.debug("debug:进入到testLog4j"); logger.error("error:进入到testLog4j"); }

    控制台:

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0orrS2wq-1630250334555)(%E4%B8%80%20%E7%AE%80%E4%BB%8B.assets/image-20210820105630474.png)]

    注意:

    Log4j可以代替输出语句 System.out.println();

    7.分页

    为什么要分页:

    • 减少数据的处理量
    1.使用limit分页: 语法:select * from user limit startIndex,pageSize select * from user limit 3 #{0,n}

    结合Map使用:

    UserMapper

    //分页查询 List<User> selUserByLimit(Map<String,Integer> map);

    UserMapper.xml

    <select id="selUserByLimit" resultType="User" parameterType="map"> select * from user limit #{startIndex},#{pageSize} </select>

    测试类

    @Test public void testLimit(){ SqlSession session = MybatisUtil.getsqlSession(); UserMapper mapper = session.getMapper(UserMapper.class); Map<String,Integer> map=new HashMap<String,Integer>(); map.put("startIndex",1); map.put("pageSize",2); List<User> users = mapper.selUserByLimit(map); for (User user : users) { System.out.println(user); } session.close(); } 2.RowBounds分页(了解) 3.分页插件 8.注解开发 1.面向接口编程
    • 根本原因:解耦,可扩展,分分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性好

    • 三面向的区别

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

    1.注解在接口上实现

    public interface UserMapper2 { //注解开发 @Select("select * from user") List<User> selAll(); }

    2.添加到核心配置文件中

    <mappers> <mapper class="com.kuang.dao.UserMapper2"></mapper> </mappers>

    3.测试类

    @Test public void test(){ SqlSession sqlSession = MybatisUtil.getsqlSession(); UserMapper2 mapper = sqlSession.getMapper(UserMapper2.class); List<User> users = mapper.selAll(); for (User user : users) { System.out.println(user); } sqlSession.close(); }

    本质:反射机制实现

    底层:动态代理!

    优点:使开发更简单了

    缺点:当数据库的字段名和实体类的属性名不一致的时候,就实现不了

    3.CRUD

    可以在工具类中设置自动提交事务:

    java

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

    mapper接口:

    public interface UserMapper { //注解开发 查询 @Select("select * from user") List<User> selAll(); //根据id和用户名查询 @Select("select * from user where id=#{id1} and name =#{name1}") User selUserById(@Param("id1") int id,@Param("name1") String name); //添加 @Insert("insert into user (id,name,pwd) value(#{id},#{name},#{password})") int addUser(User user); //删除 @Delete("delete from user where id=#{id}") int deleteUser(@Param("id") int id); //修改 @Update("update user set name=#{name},pwd=#{password} where id=#{id}") int updateUser(User user); }

    测试类:

    注意:我们必须把接口mapper绑定到核心配置文件中

    public class UserMapperTest { @Test public void testSelAll(){ SqlSession sqlSession = MybatisUtil.getsqlSession(); UserMapper2 mapper = sqlSession.getMapper(UserMapper2.class); List<User> users = mapper.selAll(); for (User user : users) { System.out.println(user); } sqlSession.close(); } @Test public void testSelUserById(){ SqlSession sqlSession = MybatisUtil.getsqlSession(); UserMapper2 mapper = sqlSession.getMapper(UserMapper2.class); User user = mapper.selUserById(1,"李白"); System.out.println(user); sqlSession.close(); } @Test public void testAddUser(){ SqlSession sqlSession = MybatisUtil.getsqlSession(); UserMapper2 mapper = sqlSession.getMapper(UserMapper2.class); int i = mapper.addUser(new User(7,"吕布","333445")); System.out.println(i); sqlSession.close(); } @Test public void testdeleteUser(){ SqlSession sqlSession = MybatisUtil.getsqlSession(); UserMapper2 mapper = sqlSession.getMapper(UserMapper2.class); int i = mapper.deleteUser(7); System.out.println(i); sqlSession.close(); } @Test public void testUpdateUser(){ SqlSession sqlSession = MybatisUtil.getsqlSession(); UserMapper2 mapper = sqlSession.getMapper(UserMapper2.class); int i = mapper.updateUser(new User(6,"吕布1","3334451")); System.out.println(i); sqlSession.close(); } }

    关于@Param()注解:

    • 如果是参数是基本数据类型或String类型,需要加上
    • 如果是引用类型,不需要用
    • 如果只有一个基本数据类型,可以忽略,但是建议加上
    • 我们在sql语句引用的就是@Param()里面的参数

    #{} 和 ${}区别

  • # 将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。如:order by #{user_id},如果传入的值是 name , 那么解析成sql时的值为order by “name”, 如果传入的值是id,则解析成的sql为order by “id”.
  • $ 将传入的数据直接显示生成在sql中。如:order by ${user_id},如果传入的值是name, 那么解析成sql时的值为order by name, 如果传入的值是id,则解析成的sql为order by id.
  • 综上所述,$ {}方式会引发SQL注入的问题、同时也会影响SQL语句的预编译,所以从安全性和性能的角度出发,能使用#{}的情况下就不要使用 ${}。

    ${} 在什么情况下使用呢?

    有时候可能需要直接插入一个不做任何修改的字符串到SQL语句中。这时候应该使用${}语法。

    比如,动态SQL中的字段名,如:ORDER BY ${columnName}

    <select id="queryMetaList" resultType="Map"> Select * from name where name = ${name} ORDER BY ${age} </select>

    由于${}仅仅是简单的取值,所以以前sql注入的方法适用此处,如果我们order by语句后用了${},那么不做任何处理的时候是存在sql注入危险的。

    9.Lombok

    Project Lombok 是一个 Java 库,可自动插入您的编辑器并构建工具,为您的 Java 增添趣味。 永远不要再编写另一个 getter 或 equals 方法,通过一个注释,您的类就有一个功能齐全的构建器,自动化您的日志变量等等。

    @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 @var experimental @var @UtilityClass Lombok config system

    使用步骤:

  • 在项目中导入Lombok依赖
  • <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> </dependency>
  • 在实体类上加上注解即可

    @Date @AllArgsConstructor @NoArgsConstructor
  • @Date注解:无参构造 、get、set、toStirng、hashcode、equals

    10.多对一处理

    实体类:

    @Data public class Student { private int id; private String name; //关联老师 private Teacher teacher; } @Data public class Teacher { private int id; private String name; }

    测试环境搭建:(多名学生由一名老师授课)

  • 建实体类Teacher 、Student
  • 建立Mapper接口(TeacherMapper、StudentMapper)
  • 建Mapper.xml文件
  • 在核心配置文件中绑定注册Mapper文件或者Mapper.xml文件
  • 创建测试类
  • 1.按照查询结果嵌套 <mapper namespace="com.kuang.dao.StudentMapper"> <!--1.查出student数据库 2.根据查出的学生的tid,从而查出对应的老师--> <select id="selStudent" resultMap="studentTeacher"> select * from Student; </select> <resultMap id="studentTeacher" type="Student"> <!--一般属性--> <result column="id" property="id"/> <result column="name" property="name"/> <!--复杂属性--> <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/> </resultMap> <select id="getTeacher" resultType="Teacher"> <!-- tid 可以随便写,mybatis会自动匹配,为了代码可读性,最好填写tid--> select * from teacher where id=#{tid} </select> </mapper> 2.按照结果查询 <mapper namespace="com.kuang.dao.StudentMapper"> <!--按照结果嵌套处理--> <select id="selStudent2" resultMap="studentTeacher"> 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="sname"/> </association> </resultMap> </mapper> 11.一对多处理

    比如:一个老师对应多个学生

    按照结果嵌套

    实体类:

    @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> studentList; }

    mapper接口:

    public interface TeacherMapper { //通过id查询某个老师所教的学生 public Teacher selTeacher(@Param("id") int id); }

    mapper.xml

    <select id="selTeacher" resultMap="TeacherStudent" > select t.id id,t.name tname,s.name sname,s.id sid from teacher t,student s where t.id=s.tid </select> <resultMap id="TeacherStudent" type="Teacher" > <result column="id" property="id"/> <result column="tname" property="name"/> <!--复杂的属性,我们需要单独处理 对象:association 集合:collection javaType="" 指定属性的类型 集合中的泛型信 我们使用 ofType="" --> <collection property="student" ofType="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <result property="tid" column="id"/> </collection> </resultMap> 总结:
  • 关联 association 【多对一】
  • 集合 collection 【一对多】
  • JavaType ofType
  • JavaType 用于指定实体类中属性的类型
  • ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型
  • 注意点:

    • 保证SQL的可读性,尽量保证通俗易懂
    • 注意一对多和多对一,属性名和字段的问题
    • 如果问题不好排查错误,可以使用日志,建议使用Log4j
    12.动态SQL

    什么叫做动态SQL:根据不同条件拼接 SQL 语句

    和JSTL 或任何基于类 XML 语言的文本处理器相似。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。 if choose (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 '博客作者', creat_time datetime not null comment '创建时间', views int(30) not null comment '浏览量' )ENGINE=InnoDB DEFAULT CHARSET=utf8

    导入依赖

    配置核心配置文件

    创建实体类

    创建实体类对应的mapper接口 mapper.xml文件

    @Data public class Blog { private String id; private String title; private String author; private Date creatTime; private int views; } public interface BlogMapper { //插入数据 int addBlog(Blog blog); //条件查询 List<Blog> selBlogIF(Map map); } if <insert id="addBlog" parameterType="Blog"> insert into blog (id,title,author,creat_time,views) values(#{id},#{title},#{author},#{creatTime},#{views}) </insert> <select id="selBlogIF" parameterType="map" resultType="Blog"> select * from blog <where> <!--会自动省略第一个if里面的 and--> <if test="title!=null"> and title=#{title} </if> <if test="author!=null"> and author=#{author} </if> </where> </select> SQL片段

    有时候,我们可能需要将一些功能块提取出来,方便重复使用

    • 使用SQL标签抽取公共的部分
    <sql id="title-author" > <if test="title!=null"> and title=#{title} </if> <if test="author!=null"> and author=#{author} </if> </sql>
    • 在需要使用的地方使用include标签引用即可
    <select id="selBlogIF" parameterType="map" resultType="Blog"> select * from blog <where> <include refid="title-author"></include> </where> </select>

    注意事项:

    • 最好基于单表来定义SQL
    foreach <!--select * from post where id in (1,3,4,6) map集合里面存在一个list集合 --> <select id="selectPostIn" resultType="domain.blog.Post" parameterType="map"> SELECT * FROM POST WHERE ID in <foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} </foreach> </select>

    动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了

    建议: 先在Mysql中写出完整的SQL,在对应的去修改称为我们的动态SQL

    13.缓存 1.简介 查询 : 连接数据库,耗资源! 一次查询的结果,给他暂存在一个可以直接取到的地方!—>内存 : 缓存 我们再次查询相同数据的时候,直接走缓存,就不用走数据库了

    1.什么是缓存:

    • 存在内存中的临时数据

    2.为什么使用缓存?

    • 减少和数据库的交互次数,减少系统开销,提高系统效率。

    3.什么样的数据能使用缓存?

    • 经常查询并且不经常改变的数据
    2.Mybatis缓存

    MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。

    MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存

    • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
    • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
    • 为了提扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
    3.一级缓存

    一级缓存也叫本地缓存:SqlSession

    • 与数据库同一次会话期间查询到的数据会放在本地缓存中。
    • 以后如果需要获取相同的数据,直接从缓存中拿,没有必要再去查询数据

    测试步骤:

  • 开启日志!
  • 测试在一个Session中查询两次相同的记录
  • 查看日志输出
  • @Test public void test(){ SqlSession sqlSession = MybatisUtil.getsqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.selUserById(1); System.out.println(user); System.out.println("-----------------------------"); User user1 = mapper.selUserById(1); System.out.println(user1); System.out.println(user==user1); sqlSession.close(); }

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XrFx8khk-1630250334557)(%E4%B8%80%20%E7%AE%80%E4%BB%8B.assets/image-20210828232041787.png)]

    缓存失效的情况:

    • 查询不同的东西
    • 增删改操作,可能会改变原来的数据,所以必定会刷新缓存!
    • 查询不同的Mapper.xml 手动清理缓存!
    • sqlsession.clearCache(); //手动清理缓存

    小结:一级缓存是默认开启的,只在一次sqlSession中有效,也就是拿到连接到关闭连接区间段.

    4.二级缓存

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

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

    工作机制 :

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

    步骤:

    1 开启全局缓存

    <!--显式的开启全局缓存--> <setting name="cacheEnabled" value="true"/>

    2 在要使用二级缓存的mapper.xml文件中开启 (常用)

    <!--在当前mapper.xml中使用二级缓存,一级缓存关闭时的数据会存放放到二级缓存中--> <cache/>

    3 也可以自定义参数

    <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>

    4 测试

    ​ 1.问题:我们需要将实体类序列化! 否则就会报错 (implement serializable)

    小结:

    • 只要开启二级缓存.在同一个Mapper.xml下有效
    • 所有的数据都会先放在一级缓存中;
    • 只有当会话提交,或者关闭的时候,才会提交到二级缓存中!
    5.mybatis缓存原理

    6.自定义缓存—ehcache

    是什么?

    EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。

    使用前先导包

    <!-- mvnrepository/artifact/org.mybatis.caches/mybatis-ehcache --> <dependency> <groupId>org.mybatis.caches</groupId> <artifactId>mybatis-ehcache</artifactId> <version>1.2.1</version> </dependency>

    在mapper.xml中指定使用我们的自定义缓存

    <cache type="com.domain.something.MyCustomCache"/>

    ehcache.xml

    <?xml version="1.0" encoding="UTF-8"?> diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下: user.home – 用户主目录 user.dir – 用户当前工作目录 java.io.tmpdir – 默认临时文件路径 <diskStore path="java.io.tmpdir/Tmp_EhCache"/> defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。 name:缓存名称。 maxElementsInMemory:缓存最大数目 maxElementsOnDisk:硬盘最大缓存个数。 eternal:对象是否永久有效,一但设置了,timeout将不起作用。 overflowToDisk:是否保存到磁盘,当系统当机时 timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。 timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。 diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false. diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。 diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。 memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。 clearOnFlush:内存数量最大时是否清除。 memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。 FIFO,first in first out,这个是大家最熟的,先进先出。 LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。 LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。 <defaultCache eternal="false" maxElementsInMemory="10000" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="1800" timeToLiveSeconds="259200" memoryStoreEvictionPolicy="LRU"/ <cache name="cloud_user" eternal="false" maxElementsInMemory="5000" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="1800" timeToLiveSeconds="1800" memoryStoreEvictionPolicy="LRU"/> 以上全部来自哔哩哔哩狂神mybatis讲解视频内容

    本文标签: 文档mybatis