mybatis编写步骤

1、CRUD

总体步骤都是编写接口,编写mapper的SQL语句,进行测试

注意增删改需要提交事务 commit()

1、namespace

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

2、select

待选参数

  • id : 对应的方法名
  • resultType :sql语句执行的返回值
  • parameterType : 传入参数的类型

3、insert

4、update

5、delete

代码

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

    <select id="getUserById" parameterType="int" resultType="com.kk.pojo.User">
        select * from mybatis.user where id = #{id}
    </select>

    <!--对象中的属性可以直接取出-->
    <insert id="addUser" parameterType="com.kk.pojo.User">
        insert into mybatis.user (id,name,password) values(#{id},#{name},#{password});
    </insert>

    <update id="updateUser" parameterType="com.kk.pojo.User">
        update mybatis.user set name = #{name},password=#{password} where id = #{id};
    </update>

    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id=#{id};
    </delete>

6、易错区域

  • 标签匹配接口不要匹配错

  • resource 绑定mapper,需要使用路径,/连接

  • NullPointerException,没有注册资源,或者多次定义变量

  • xml文件中存在中文乱码

  • maven资源导入问题,如上所提

7、Map输入

当我们的实体类需要很多参数时,考虑使用map进行多参数的输入构造

public void addUser2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);

        Map<String, Object> map = new HashMap<>();
        map.put("id",1);
        map.put("name","粉");
        map.put("password","123456");

        mapper.addUser2(map);

        sqlSession.commit();
        sqlSession.close();

    }
<insert id="addUser2" parameterType="map">
    insert into mybatis.user (id,name,password) values(#{id},#{name},#{password});
</insert>

总结:

对于map传递参数,直接在sql中取出key即可 parameterType="map"

对象传递参数,直接在sql中取对象的值即可 parameterType="com.kk.pojo.User"

只有一个基本类型参数的情况下,可以直接在sql中取得 parameterType="int"

2、配置解析

1、基本配置

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

2、环境配置(environments)

mybatis可创建多个环境,但每个SqlSessionFactory实例只能选择一种环境

学会配置多套环境

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

3、属性(properties)

通过属性(properties)优化配置

db.properties

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

在核心配置中引入

<properties resource="db.properties"/>
  • 可以直接引入外部文件
  • 可以在其中增加一些属性配置
  • 如果有相同字段,优先使用外部配置文件(过程是先读取代码中增加的字段信息,在读取外部文件,然后进行覆盖)

4、类型别名(typeAliases)

  • 类型别名可为 Java 类型设置一个缩写名字
  • 它仅用于 XML 配置,意在降低冗余的全限定类名书写
<!--实体类起别名-->
<typeAliases>
    <typeAlias type="com.kk.pojo.User" alias="User"/>
</typeAliases>

也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean

扫描实体类的包,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名,即首字母小写类名

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

实体类较少时,第一种

较多,则第二种

第一种优点在于DIY别名

第二种也可通过添加对应类的注解实现别名定义

@Alias("user")
public void getUser(){}

5、设置(setting)

image-20220503201500576

image-20220503201517781

image-20220503201640798

6、其他配置

7、映射器(mappers)

MapperRigisty:注册绑定我们的mapper文件;

方式一:(推荐使用,配合maven过滤配置)

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

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

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

注意点:

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

方式三:使用扫描包进行注册绑定

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

注意点:

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

8、作用域(Scope)和生命周期

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

SqlSessionFactoryBuilder

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

SqlSessionFactory

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

SqlSession

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

image-20220503203843624

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

1、问题所在以及简单解决方法

类中所定义的字段和数据库中存储的字段不一致

源代码:

<select id="getUserList" resultType="com.kk.pojo.User">
    select id,name,pwd from mybatis.user where if = #{id}
</select>

解决方法:

  • 起别名
<select id="getUserList" resultType="com.kk.pojo.User">
    select id,name,pwd as password from mybatis.user where if = #{id}
</select>

2、resultMap

结果集映射

<!--结果集映射-->
<resultMap id="UserMap" type="User">
    <!--column数据库中的字段,property实体类中的属性-->
    <result column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="pwd" property="password"/>
</resultMap>

<select id="getUserById" resultMap="UserMap">
    select * from mybatis.user where id = #{id}
</select>
  • 需要什么改什么

4、日志

4.1、日志工厂

排错需要日志

曾经:sout、debug

现在:日志工厂

image-20220503211220632

  • SLF4J (掌握)
  • LOG4J (掌握)
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING (掌握)
  • NO_LOGGING
<settings>
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

image-20220503212510215

6.2、LOG4J

1、进行导入

<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

2、通过文件配置

#将等级为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>

4、log4j的使用,直接测试

image-20220503215311667

简单使用

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

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

static Logger logger = Logger.getLogger(UserDaoTest.class);

5、分页

目的:

  • 减少数据处理量

5.1使用Limit分页

SELECT * FROM user limit startIndex,pageSize;
SELECT * FROM user limit 3;#[0,n]

使用Mybatis实现分页,核心SQL

1.接口

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

2.Mapper.xml

<!--分页-->
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
	select * from mybatis.user limit #{startIndex},#{pageSize}
</select>

3.测试

@Test
public void getUserByLimit(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    HashMap<String, Integer> map = new HashMap<>();
    map.put("startIndex",1);
    map.put("pageSize",2);
    List<User> userList = mapper.getUserByLimit(map);

    for (User user:userList) {
        System.out.println(user);
    }
    sqlSession.close();
}

5.2、RowBounds分页

6、使用注解开发

1.注解在接口上实现

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

2.需要在核心配置文件中绑定接口

<mappers>
    <mapper class="com.kk.dao.UserDao"/>
</mappers>

3.测试

@Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);

        List<User> users = mapper.getUserList();
        for(User user:users){
            System.out.println(user);
        }

        sqlSession.close();
    }

本质:反射机制实现

底层:动态代理

image-20220503224804385

6.1、CRUD

在工具类创建时实现自动提交事务

openSession设置为true

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

编写接口

public interface UserDao {
    @Select("select * from user")
    List<User> getUserList();

    //查看
    //方法存在多个参数,所有参数前面必须加上@Param("id")注解 取别名
    //#{id}依赖于@Param("id")里的名称
    @Select("select * from user where id = #{id}")
    User getUserById(@Param("id") int id,@Param("name") String name);

    @Insert("insert into user(id,name,password) values(#{id},#{name},#{password})")
    int addUser(User user);

    @Update("update user set name=#{name},password=#{password} where id=#{id}")
    int updateUser(User user);

    @Delete("delete from user where id = #{uid}")
    int deleteUser(@Param("uid")int id);
}

测试

【要点】 注意要在配置文件(mybatis-config.xml)中注册绑定接口

关于@Param()注解

  • 基本类型的参数或者String类型,要加上
  • 引用类型不用加
  • 只有一个基本类型,可以不加,建议加上
  • sql中引用的是@Param()中设定的属性名

7、Lomkob(降低可阅读型)

1.idea中安装lombok插件

2.项目中导入lombok的jar包

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

@Data : 无参构造,get、set、tostring、hashcode

@AllArgsConstructor, @NoArgsConstructor 有参和无参构造

8、多对一处理

测试环境搭建 编号:07

1.导入lombok

2.新建实体类Teacher,Student

3.建立Mapper接口

4.建立Mapper.xml

5.注册绑定Mapper

6.查询

按照查询嵌套处理(子查询)

<!--
        1.查询出所有的学生信息
        2.根据查询出来的学生的tid,寻找对应的老师
    -->
<select id="getStudent" resultMap="StudentTeacher">
    select * from student
</select>

<resultMap id="StudentTeacher" type="Student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <!--
            复杂的属性,需要单独处理
            对象:association
            集合: collection
        -->
    <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
    select * from teacher where id = #{id}
</select>

按照结果嵌套处理(联表查询)

<!--按照结果嵌套查询-->
<select id="getStudent2" resultMap="StudentTeacher2">
    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
            集合: collection
        -->
    <association property="teacher" javaType="Teacher">
        <result property="name" column="tname"/>
    </association>
</resultMap>

9、一对多处理

一个老师对应多个学生

@Data
public class Student {
    private int id;
    private String name;

    private Teacher teacher;
}

@Data
public class Teacher {
    private int id;
    private String name;

    //一个老师拥有多个学生
    private List<Student> students;
}

按照结果嵌套处理

<!--按结果查询-->
<select id="getTeacher" resultMap="TeacherStudent">
    select s.id sid, s.name sname, t.name tname, t.id tid
    from student s,teacher t
    where s.tid = t.id and t.id = #{tid}
</select>

<resultMap id="TeacherStudent" type="Teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <!--
            复杂的属性,需要单独处理
            对象:association
            集合: collection
            javaType="" 指定属性
            集合中的泛型信息,我们使用ofType获取
        -->
    <collection property="students" ofType="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>

按照查询嵌套处理(子查询)

<!--子查询-->
<select id="getTeacher2" resultMap="TeacherStudent2">
    select * from mybatis.teacher t where t.id = #{tid}
</select>

<resultMap id="TeacherStudent2" type="Teacher">
    <!--column表示是子查询所对应的那个值-->
    <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>

<select id="getStudentByTeacherId" resultType="Student">
    select * from mybatis.student where tid = #{tid}
</select>

1.关联 -association

2.集合 - collection

3.javaType & ofType

​ 1.JavaType 用来指定实体类中属性的类型

​ 2.ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型

注意点:

  • 为了保证SQL可读性,尽量保证通俗易懂

  • 注意一对多和多对一的属性名和字段

  • 可以使用日志辅助排查错误

面试高频

  • Mysql引擎
  • InnoDB底层
  • 索引
  • 索引优化

10、动态SQL

动态SQL:根据不同的条件生成不同的SQL语句

使用动态 SQL 并非一件易事,但借助可用于任何 SQL 映射语句中的强大的动态 SQL 语言,MyBatis 显著地提升了这一特性的易用性。

如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 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 '博客作者',
`create_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8

创建工程

1.导包

2.编写配置文件


3.编写实体类

@Data
public class Blog {
    private int id;
    private String title;
    private String author;
    private Date createTime;
    private int views;
}

4.编写实体类对应Mapper接口 和Mapper.xml文件

IF

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

choose (when, otherwise)

单选,加不加and都可以

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

    </where>
</select>

trim (where, set)

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

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

update时记得加逗号

<update id="updateBlog" parameterType="map">
    update blog
    <set>
        <if test="title != null">
            title = #{title},
        </if>
        <if test="author != null">
            author = #{author}
        </if>
    </set>
    where id = #{id}
</update>

foreach

<!--blog别名不区分大小写-->
<select id="queryBlogForeach" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <!--ids为map内部传入的键值名称,遍历时ids内部的值赋值给id-->
        <foreach collection="ids" item="id" open="and (" close=")" separator="or">
            id = #{id}
        </foreach>
    </where>
</select>

SQL片段

重用SQL

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

注意事项:

  • 最好基于单表定义SQL片段
  • 不要存在where标签

动态SQL就是拼接SQL语句

建议:

  • 先在Mysql中写出完整的SQL,再对应修改动态SQL

11、缓存

11.1、 简介

每次连接数据库会消耗资源,一次查询的结果可以保存在内存中,再次查询相同数据时,直接从缓存中查询

11.2、一级缓存

  • 一级缓存也叫本地缓存

MyBatis 默认开启了一级缓存,一级缓存是在 SqlSession 层面进行缓存的。

即,同一个 SqlSession ,多次调用同一个 Mapper 和同一个方法的同一个参数,只会进行一次数据库查询,然后把数据缓存到缓冲中,以后直接先从缓存中取出数据,不会直接去查数据库。但是不同的 SqlSession 对象,因为不用的 SqlSession 都是相互隔离的,所以相同的 Mapper、参数和方法,它还是会再次发送到 SQL 到数据库去执行,返回结果。

缓存失效的情况:

  1. 查询不同的东西

  2. 增删改操作,可能会改变原来数据,必定刷新缓存!

  3. 查询不同Mapper.xml

  4. 手动清理缓存

image-20220515215259022

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

一级缓存就是一个map

11.3、二级缓存

  • 二级缓存也叫全局缓存,由于一级缓存作用域太低,因此诞生二级缓存
  • 基于namespace级别的缓存,一个命名空间,对应一个二级缓存
  • 工作机制
    • 一个会话查询一条数据,放在一级缓存
    • 若当前会话关闭了,这个会话的一级缓存就没了;我们想要关闭会话后将原一级缓存中的数据保存到二级缓存
    • 新的会话从二级缓存中读取内容
    • 不同mapper查出的数据会放在自己对应的缓存(map)中

为了解决这个问题,需要手动开启二级缓存,在 SqlSessionFactory 层面给各个 SqlSession 对象共享。默认二级缓存是不开启的,需要手动进行配置。

步骤:

  1. 开启全局缓存
    image-20220515215655983
<settings>
    <!--显式开启全局缓存-->
    <setting name="cacheEnabled	" value="true"/>
</settings>
  1. 在要使用二级缓存的Mapper中开启

    <!--当前mapper使用二级缓存-->
    <cache/>
    

    自定义参数

    <!--当前mapper使用二级缓存-->
    <cache
           eviction="FIFO"
           flushInterval="60000"
           size="512"
           readOnly="true"/>
    
    1. 测试

      ​ 1.问题:实体类序列化

    小结:

    • 开启了二级缓存,在同一个Mapper下就有效
    • 所有数据搜会放在以及缓存中
    • 会话提交或者关闭时,才会提交到二级缓存中

11.4、缓存原理

image-20220515222901907

11.5、自定义缓存

导入第三方缓存处理包

<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.1.0</version>
</dependency>

posted @   吃四日常  阅读(159)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示