MyBatis

    科技2022-07-10  151

    1、简介

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

    1.1获取Mybatis

    maven <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> Github https://github.com/search?q=Mybatis&type=中文文档 https://mybatis.org/mybatis-3/zh/index.html

    1.2 持久化

    数据持久化

    持久化就是将程序的数据在持久化状态和瞬时状态转化的过程内存:断电即失数据库(jdbc)、io文件持久化生活:冷藏、罐头

    为什么要持久化?

    有一些对象,不能丢失内存太贵了

    1.3 持久层

    Dao层、Service层、Controller层

    完成持久化工作的代码块层界限十分明显

    1.4为什么需要Mybatis

    帮程序员把数据存入数据库方便传统的JDBC代码太复杂了不用Mybatis也可以,更容易上手。技术没有高低之分

    2、第一个程序

    2.1依赖

    pom.xml

    <!--mysql驱动--> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> </dependencies>

    2.2 核心配置

    mybatis-config.xml

    <configuration> <environments default="development"> <environment id="development"> <!--transactionManager事务管理--> <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&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="123"/> </dataSource> </environment> </environments> <!--every Mapper.xml need to be registered in the mybatis core configuration file--> <mappers> <mapper resource="com/zhu/dao/userMapper.xml"/> </mappers> </configuration>

    maven由于约定大于配置,配置文件可能无法被导出或者生效,解决方案 pom.xml

    <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>

    2.3作用域(Scope)

    SqlSessionFactoryBuilder:一旦创建了 SqlSessionFactory,就不再需要它了 SqlSessionFactory:SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在 SqlSession:每个线程都应该有它自己的 SqlSession 实例,SqlSession 的实例不是线程安全的,因此是不能被共享的。换句话说,每次收到 HTTP 请求,就可以打开一个 SqlSession,返回一个响应后,就关闭它。这个关闭操作很重要

    3、CRUD

    3.1、namespace

    namespace中的包名要和Dao/mapper接口的包名一致

    3.2、select

    id:对应的方法名resultType:sql语句的返回值!parameter:参数类型

    1、编写接口

    List<User> getUserList();

    2、写mapper

    <select id="getUserList" resultType="com.zhu.pojo.User"> select * from user </select>

    3、测试

    @Test public void test() { // 获取sqlSession对象 SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.getUserList(); for (User user : userList) { System.out.println(user); } // 关闭sqlSession sqlSession.close(); }

    3.3、insert

    List<User> getUserList(); <insert id="addUser" parameterType="com.zhu.pojo.User"> insert into user(id,name,pwd) values(#{id},#{name},#{pwd}) </insert>

    重点:增删改需要提交事务

    sqlSession.commit();

    3.4、update

    3.5、delete

    4、配置解析

    4.1、核心配置文件

    mybatis-config.xml

    4.2、环境配置

    学会配置多套运行环境

    4.3、属性(properties)

    db.properties

    4.4、类型别名(typeAliases)

    类型别名可为 Java 类型设置一个缩写名字降低冗余的全限定类名书写 // 给类取别名 <typeAliases> <typeAlias type="com.zhu.pojo.User" alias="User"/> </typeAliases>

    //给包取别名 会使用 Bean 的首字母小写的非限定类名来作为它的别名

    <typeAliases> <package name="com.zhu.pojo"/> </typeAliases>

    4.5、设置(settings)

    mapUnderscoreToCamelCase (驼峰命名)logImpl (日志实现)

    4.6、映射器

    MapperRegister :注册绑定我们的Mapper文件

    <mappers> <mapper resource="com/zhu/dao/userMapper.xml"/> </mappers>

    4.7、生命周期和作用域

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

    SqlSessionFactoryBuilder

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

    SqlSessionFactory

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

    SqlSession:

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

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

    5.1、问题

    数据库字段 属性名

    sql

    <select id="findUserById" parameterType="int" resultType="user"> select * from user where id = #{id} </select>

    查找pwd为null

    5.2、resultMap(结果集映射)十分重要!

    id name pwd id name password

    结果集映射

    <mapper namespace="com.zhu.dao.UserMapper"> <resultMap id="UserMap" type="User"> <result column="id" property="id"/> <result column="name" property="name"/> <result column="pwd" property="password"/> </resultMap> <select id="findUserById" parameterType="int" resultMap="UserMap"> select * from user where id = #{id} </select> </mapper> resultMap 元素是 MyBatis 中最重要最强大的元素ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。这就是 ResultMap 的优秀之处——你完全可以不用显式地配置它们。

    6、日志

    6.1 日志工厂

    如果数据库操作出现异常,我们需要排错,要用到日志!

    LOG4JSTDOUT_LOGGING

    核心配置里配置日志

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

    6.2 LOG4J

    什么是log4j

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

    1、导maven

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

    2、log4.properties

    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/zhu.txt 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、配置实现

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

    简单使用 1、导入import org.apache.log4j.Logger;的包 2、日志对象,参数为当前类的class

    Logger logger = Logger.getLogger(UerDaoTest.class); public void testLog4j(){ logger.info("info:进入了tesLog4j"); // 相当于system.out logger.debug("debug:进入debug模式"); logger.error("error:error模式"); }

    7、分页

    7.1 使用limit分页

    select * from user limit startIndex,pageSize; 第一个参数:从第几个参数开始(0、1、2…)往后 查询几个数据

    1、接口

    //分页 List<User> getUserByLimit(Map<String,Integer> map);

    2、Mapper.xml

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

    3、测试

    @Test public void getUserByLimit(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); HashMap<String, Integer> map = new HashMap<String, Integer>(); map.put("startIndex",2); map.put("pageSize",2); // 从第2个开始取2个 List<User> userByLimit = mapper.getUserByLimit(map); for (User user : userByLimit) { System.out.println(user); } sqlSession.close(); }

    7.2 RowBounds分页

    7.3 分页插件

    8、Mybatis注解开发

    8.1 使用注解开发

    1、注解在接口上实现

    @Select("select * from user") List<User> getUsers();

    2、在核心配置绑定接口

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

    3、测试 本质:反射机制实现 底层:动态代理!

    8.2 Mybatis生命周期

    1、Resources获取加载全局配置文件 2、实例化SqlSessionFactoryBuilder 3、实例化SqlSessionFactory

    8.3 CRUD

    编写接口,增加注解

    @Select("select * from user") List<User> getUsers(); // 方法存在多个参数,所有的参数必须加上@Param @Select("select * from user where id = #{id}") User getUserById(@Param("id") int id); @Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password})") int addUser(User user); @Update("update user set name=#{name},pwd=#{password} where id = #{id}") int updateUser(User user); @Delete("delete from user where id = #{id}") int deleteUser(@Param("id") int id);

    重点:我们必须要将接口注册绑定到mybatis核心配置文件中!

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

    关于@param()注解

    基本类型的参数(byte,short,int,long,float,double,char,boolean)或者String类型,需要加上引用类型不需要加我们在Sql语句中引用的就是@Param()中设定的属性值

    9、多对一处理

    Mybatis实现查询所有的学生信息,以及对应的老师信息 sql语句

    select s.id,s.name,t.name from student s,teacher t where s.tid = t.id

    按照查询嵌套处理

    思路

    查询所有的学生信息根据查询出来的学生的tid,寻找到对应的老师 !(子查询) <select id="getStudent" resultMap="StudentTeacher"> select * from student </select> <resultMap id="StudentTeacher" type="com.zhu.pojo.Student"> <result property="id" column="id"/> <result property="name" column="name"/> <!-- 复杂的属性,我们需要单独处理, 对象:association 集合:collection --> <association property="teacher" column="tid" javaType="com.zhu.pojo.Teacher" select="getTeacher"/> </resultMap> <select id="getTeacher" resultType="com.zhu.pojo.Teacher"> select * from Teacher where id = #{tid} </select>

    10、一对多

    。。。

    小结

    1.关联 association 【多对一】对象 2.集合 collection 【一对多】 集合 3. JavaType & ofType

    JavaType用来指定实体类中属性的名称ofType用来指定映射到List泛型中的约束类型

    11、动态SQL

    根据不同的条件生成不同的SQL

    动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。 使用动态 SQL 并非一件易事,但借助可用于任何 SQL 映射语句中的强大的动态 SQL 语言,MyBatis 显著地提升了这一特性的易用性。 如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。 if choose (when, otherwise) trim (where, set) foreach

    if

    <select id="queryBlogIF" parameterType="map" resultType="com.zhu.pojo.Blog"> select * from blog where 1=1 <if test="title != null"> and title = #{title} </if> <if test="author != null"> and author = #{author} </if> </select>

    trim (where)

    where标签:子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

    <select id="queryBlogIF" parameterType="map" resultType="com.zhu.pojo.Blog"> select * from blog <where> <if test="title != null"> and title = #{title} </if> <if test="author != null"> and author = #{author} </if> </where> </select>

    choose (when, otherwise)

    相当于Java中的switch语句,只会进入一个when语句 <select id="queryBlogChoose" parameterType="map" resultType="com.zhu.pojo.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

    自动删除sql语句中无效逗号

    <update id="updateBlog" parameterType="com.zhu.pojo.Blog"> update blog <set> <if test="title != null"> title = #{title}, </if> <if test="author != null"> author = #{author} </if> </set> where id = #{id} </update>

    所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面去执行一个逻辑代码

    12、缓存

    12.1 简介

    查询:连接数据库,耗资源! 解决方法:一次查询的结果,给他暂存在一个可以直接取到的地方!--> 内存 再次查询相同数据时,直接走缓存,就不需要重新读取数据库

    1 什么是缓存[Cache]?

    存在内存中的临时数据解决了高并发系统的性能问题

    2 为什么使用缓存

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

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

    经常查询并且不经常改变的数据

    12.2 Mybatis缓存

    Mybatis默认定义了两级缓存:一级缓存和二级缓存默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)二级缓存需要手动开启和配置,是基于namespace级别的缓存可以通过实现Cache接口来自定义二级缓存

    12.3 一级缓存

    也叫 本地缓存,SqlSession级别

    一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间。

    12.4 二级缓存

    小结

    只要开启了二级缓存,在同一个Mapper下就有效所有的数据都会先放在一级缓存中只有当会话提交,或者关闭的时候,才会提交到二级缓存中去。

    mybatis 映射文件加载方式(resource与class)

    resource

    <mappers> //注意路径书写方式 <mapper resource="com/das/pojo/TeacherDao.xml"/> </mappers>

    class

    接口文件(interface)与映射文件(*.xml)在同一路径下,且接口名与映射文件名相同,并且映射文件命名空间为接口全类名的情况.

    <mappers> //class的内容是接口的全类名 <mapper class="com.das.dao.TeacherDao"/> </mappers>
    Processed: 0.020, SQL: 8