ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Mybatis基础

2021-09-17 19:01:49  阅读:124  来源: 互联网

标签:缓存 name 基础 log4j user Mybatis id select


1、简介

1. 什么是Mybatis

  • MyBatis 本是apache的一个开源项目iBatis,iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。

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

  • 它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。

2. 持久化

  • 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
  • java 内存中的数据断电即失
  • 数据库(Jdbc),io文件可以做到持久化

3. 优点

  • 帮助程序员将数据存入到数据库中
  • 传统的JDBC代码太复杂了,简化,框架,自动化
  • 简单易学:本身就很小且简单。没有任何第三方依赖。
  • 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。
  • 解除sql与程序代码的耦合,sql和代码的分离,提高了可维护性。
  • 提供映射标签,支持对象与数据库的orm字段关系映射
  • 提供对象关系映射标签,支持对象关系组建维护
  • 提供xml标签,支持编写动态sql。

2. Mybatis程序

  • 每个MyBatis应用程序主要都是使用SqlSessionFactory实例的,一个SqlSessionFactory实例可以通过SqlSessionFactoryBuilder获得。SqlSessionFactoryBuilder可以从一个xml配置文件或者一个预定义的配置类的实例获得。

1. 导入maven依赖

<!--mysqlq驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.12</version>
</dependency>
<!--mybatis-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.4</version>
</dependency>
<!--junit测试-->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

2. 编写核心配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<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?userSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

3. 编写工具类

构建SqlSessionFactory 的实例非常简单,建议使用类路径下的资源文件进行配置。 但也可以使用任意的输入流(InputStream)实例

//sqlSessionFactory --> sqlSession
public class MybatisUtils {

    static SqlSessionFactory sqlSessionFactory = null;

    static {
        try {
            //使用Mybatis第一步 :获取sqlSessionFactory对象
            //String resource = "org/mybatis/example/mybatis-config.xml";
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例.
    // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
    public static SqlSession getSqlSession(){
        //实现自动提交事务
        return sqlSessionFactory.openSession(true);
    }
}

4. 编写代码

  • 实体类
//实体类
public class User {
    private int id;
    private String name;

    public User() {
    }

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

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

    @Override
    public String toString() {
        return "User{" +
            "id=" + id +
            ", name='" + name + '\'' +
            '}';
    }
}
  • Dao接口
public interface UserDao {
    List<User> getUserList();
}
  • Mapper配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dao.UserDao">
    <!--sql-->
    <select id="getUserList" resultType="com.pojo.User">
        select * from user
    </select>
</mapper>
  • 注册Mapper(mybatis的核心配置文件)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration core file-->
<configuration>
    <environments default="development">
        <!--....数据源-->
    </environments>
    <!--注册Mapper-->
    <mappers>
        <mapper resource="com/dao/UserMapper.xml"/>
    </mappers>
</configuration>
  • 测试
@Test
public void test(){
    //第一步:获得SqlSession对象
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    //方式一:getMapper
    UserDao userDao = sqlSession.getMapper(UserDao.class);
    List<User> userList = userDao.getUserList();

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

    //关闭SqlSession
    sqlSession.close();
}

5.遇到的问题

  1. 配置文件没有注册
  2. 绑定接口错误
  3. 方法名不对
  4. 返回类型不对
  5. Maven导出资源问题

3. CRUD

  • 在MybatisUtils工具类创建的时候实现自动提交事务!
public static SqlSession getSqlSession(){
    return sqlSessionFactory.openSession(true);
}

1. namespace

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

2. select

  • id:就是对应的namespace中的方法名;
  • resultType : Sql语句执行的返回值;
  • parameterType : 参数类型;

编写接口

//根据id查询用户
User getUserById(int id);

sql语句

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

3. insert

主键自增,可以设置 useGeneratedKeys=”true”,然后再把 keyProperty 设置为目标属性。

<insert id="addUser" parameterType="com.pojo.User" useGeneratedKeys="true" keyProperty="id">
    insert into mybatis.user (id,name) values (#{id},#{name})
</insert>

4. Update

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

5. Delete

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

6. 万能的Map

//万能的Map
int addUser2(Map<String,Object> map);
<!--对象中的属性,可以直接取出来  传递map的key-->
<insert id="addUser2" parameterType="map">
    insert into user (id,name) values (#{userId},#{userName})
</insert>
@Test
public void addUser2(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    Map<String,Object> map = new HashMap<String, Object>();
    map.put("userId",4);
    map.put("userName","李四");

    mapper.addUser2(map);
    sqlSession.commit();
    sqlSession.close();
}
  • Map传递参数,直接在sql中取出key即可!【parameterType=“map”】
  • 对象传递参数,直接在sql中取对象的属性即可!【parameterType=“Object”】
  • 只有一个基本类型参数的情况下,可以直接在sql中取到!

7. 模糊查询

<!--方式一:参数会引起sql的注入-->
<select id="getUser1" parameterType="java.lang.String" resultType="com.pojo.User">
    select * from user where name like '%${name}%'
</select>
<!--方式二:-->
<select id="getUser2" parameterType="java.lang.String" resultType="com.pojo.User">
    select * from user where name like "%"#{name}"%"
</select>
<!--方式三:-->
<select id="getUser3" parameterType="java.lang.String" resultType="com.pojo.User">
    select * from user where name like CONCAT('%',#{name},'%')
</select>

4. 作用域和生命周期

1. SqlSessionFactoryBuilder

  • 一旦创建了 SqlSessionFactory,就不再需要它了。
  • 最佳作用域局部变量

2. SqlSessionFactory

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

3. SqlSession

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

在这里插入图片描述

5. 配置解析

1. 核心配置文件

  • mybatis-config.xml
  • Mybatis的配置文件包含了会深深影响MyBatis行为的设置和属性信息。
configuration(配置)
    properties(属性)
    settings(设置)
    typeAliases(类型别名)
    typeHandlers(类型处理器)
    objectFactory(对象工厂)
    plugins(插件)
    environments(环境配置)
    	environment(环境变量)
    		transactionManager(事务管理器)
    		dataSource(数据源)
    databaseIdProvider(数据库厂商标识)
    mappers(映射器)

2. 属性(properties)

  • 首先读取在 properties 元素体内指定的属性。
  • 然后根据 properties 元素中的 resource 属性读取类路径下属性文件,或根据 url 属性指定的路径读取属性文件,并覆盖之前读取过的同名属性。
  • 最后读取作为方法参数传递的属性,并覆盖之前读取过的同名属性。

config.properties

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

核心配置文件

<properties resource="config.properties">
  <property name="username" value="dev_user"/>
  <property name="password" value="F2Fa3!33TYyg"/>
</properties>
设置好的属性可以在整个配置文件中用来替换需要动态配置的属性值。比如:

<dataSource type="POOLED">
  <property name="driver" value="${driver}"/>
  <property name="url" value="${url}"/>
  <property name="username" value="${username}"/>
  <property name="password" value="${password}"/>
</dataSource>

3. 设置(settings)

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

设置名描述有效值默认值
cacheEnabled全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。true | falsetrue
lazyLoadingEnabled延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。true | falsefalse
logImpl指定 MyBatis 所用日志的具体实现,未指定时将自动查找。SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING未设置

4. 类型别名(typeAliases)

  • 类型别名可为 Java 类型设置一个缩写名字。

  • 它仅用于 XML 配置,意在降低冗余的全限定类名书写。

<!--可以给实体类起别名-->
<typeAliases>
    <typeAlias type="com.pojo.User" alias="User" />
</typeAliases>
  • 扫描实体类的包,它的默认别名就为这个类的类名,首字母小写!
<!--可以给实体类起别名-->
<typeAliases>
    <package name="com.pojo"/>
</typeAliases>
  • 实体上增加注解
@Alias("user")
public class User {
}

5. 环境配置(environments)

  • MyBatis 可以配置成适应多种环境

  • 不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

  • 每个数据库对应一个 SqlSessionFactory 实例

<environments default="development">
    <environment id="development">
        <transactionManager type="JDBC">
            <property name="..." value="..."/>
        </transactionManager>
        <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>
    <environment id="development2">
        <transactionManager type="JDBC">
            <property name="..." value="..."/>
        </transactionManager>
        <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>

关键点 :

  • 默认使用的环境 ID(比如:default=“development”)。
  • 每个 environment 元素定义的环境 ID(比如:id=“development”)。
  • 事务管理器的配置(比如:type=“JDBC”)。
  • 数据源的配置(比如:type=“POOLED”)。
  • 默认环境和环境 ID 顾名思义。 环境可以随意命名,但务必保证默认的环境 ID 要匹配其中一个环境 ID

事务管理器(transactionManager)

事务管理器(也就是 type="[JDBC|MANAGED]"):

  • JDBC – 这个配置直接使用了 JDBC 的提交和回滚设施,它依赖从数据源获得的连接来管理事务作用域。
  • MANAGED – 这个配置几乎没做什么。它从不提交或回滚一个连接,而是让容器来管理事务的整个生命周期(比如 JEE 应用服务器的上下文)。 默认情况下它会关闭连接。然而一些容器并不希望连接被关闭,因此需要将 closeConnection 属性设置为 false 来阻止默认的关闭行为。

数据源(dataSource)

三种内建的数据源类型(也就是 type="[UNPOOLED|POOLED|JNDI]")

  • UNPOOLED– 这个数据源的实现会每次请求时打开和关闭连接。

  • POOLED– 这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来,避免了创建新的连接实例时所必需的初始化和认证时间。

  • JNDI – 这个数据源实现是为了能在如 EJB 或应用服务器这类容器中使用,容器可以集中或在外部配置数据源,然后放置一个 JNDI 上下文的数据源引用。

6. 映射器(mappers)

  • MapperRegistry:注册绑定Mapper文件;

  • 接口和他的Mapper配置文件必须同名

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

<!-- 使用相对于类路径的资源引用 -->
<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
</mappers>
<!-- 使用完全限定资源定位符(URL) -->
<mappers>
  <mapper url="file:///var/mappers/AuthorMapper.xml"/>
  <mapper url="file:///var/mappers/BlogMapper.xml"/>
</mappers>
<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
  <mapper class="org.mybatis.builder.BlogMapper"/>
</mappers>
<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
  <package name="org.mybatis.builder"/>
</mappers>

7. 其他配置

  • typeHandlers(类型处理器)
  • objectFactory(对象工厂)
  • 数据库厂商标识(databaseIdProvider)
  • plugins(插件)
    1. mybatis-generator-core
    2. mybatis-plus
    3. 通用mapper

6. 结果映射

如何解决属性名和字段名不一致的问题?

在这里插入图片描述
在这里插入图片描述

1. 起别名

  • 只是简单地将所有的列映射到 HashMap 的键上,这由 resultType 属性指定,

  • 这样的一个 JavaBean 可以被映射到 ResultSet,就像映射到 HashMap 一样简单。

  • MyBatis 会在幕后自动创建一个 ResultMap,再根据属性名来映射列到 JavaBean 的属性上。

<select id="getUserById" resultType="com.pojo.User">
    select id,name,pwd as password from USER where id = #{id}
</select>

2. resultMap

  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
  • ResultMap 的优秀之处——你完全可以不用显式地配置它们。
<!--结果集映射-->
<resultMap id="UserMap" type="User">
    <!--column数据库中的字段,property实体类中的属性-->
    <result column="id" property="id"></result>
    <result column="name" property="name"></result>
    <result column="pwd" property="password"></result>
</resultMap>

<select id="getUserList" resultMap="UserMap">
    select * from USER
</select>

7. 多对一处理

1. 按照结果嵌套处理

<!--按照结果进行查询-->
<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 property="teacher" javaType="teacher">
        <result property="name" column="tname"></result>
    </association>
</resultMap>

2. 按照查询嵌套处理

<!--
      思路:
          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>

8. 一对多处理

1. 按照结果嵌套处理

<!--    按结果嵌套查询-->
<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>

2. 按照查询嵌套处理

<select id="getTeacher2" resultMap="TeacherStudent2">
    select * from mybatis.teacher where id = #{tid}
</select>

<resultMap id="TeacherStudent2" type="Teacher">
    <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>

3. 小结

  1. 关联-association【多对一】
  2. 集合-collection【一对多】
  3. javaType & ofType
    1. javaType 用来指定实体类中属性的类型
    2. ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!

9. 动态SQL

  • 动态SQL就是根据不同的条件生成不同的SQL语句

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

动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。

1. IF

如果传入了 “name” 参数,那么就会对 “name” 一列进行模糊查找并返回对应的结果

<select id="queryUser" parameterType="map" resultType="User">
    select * from user where 1=1
    <if test="name != null">
        and name = #{name}
    </if>
    <if test="pwd != null">
        and pwd = #{pwd}
    </if>
</select>

2. choose (when, otherwise)

MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

<select id="queryUser" parameterType="map" resultType="Blog">
    select * from user where 1=1
    <choose>
        <when test="name != null">
            name = #{name}
        </when>
        <when test="pwd != null">
            and pwd = #{pwd}
        </when>
        <otherwise>
            and id = #{id}
        </otherwise>
    </choose>
</select>

3. where

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

<select id="queryUser" parameterType="map" resultType="User">
    select * from user 
    <where>
        <if test="name != null">
            and name = #{name}
        </if>
        <if test="pwd != null">
            and pwd = #{pwd}
        </if>
    </where>
</select>

4. set

<update id="updatUser">
  update user
    <set>
      <if test="name != null">name=#{name},</if>
      <if test="pwd != null">pwd=#{pwd},</if>
    </set>
  where id=#{id}
</update>

5. trim

  • prefix:增加前缀

  • prefixOverrides:忽略第一个通过管道符分隔的文本序列

  • suffix:增加后缀

  • suffixoverride:略最后一个通过管道符分隔的文本序列

<select id="queryUser" parameterType="map" resultType="User">
    select * from user 
    <trim prefix="WHERE" prefixOverrides="AND | OR">
        <if test="name != null">
            and name = #{name}
        </if>
        <if test="pwd != null">
           and pwd = #{pwd}
        </if>
    </trim>
</select>

<update id="updatUser">
  update user
    <trim prefix="set" suffixoverride="," suffix=" where id = #{id} ">
      <if test="name != null">name=#{name},</if>
      <if test="pwd != null">pwd=#{pwd},</if>
    </trim>
</update>

6.forEach

  • 动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)
  • 它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。
  • 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
<!--select * from blog where 1=1 and id in (1,2,3) -->
<select id="queryUser" parameterType="map" resultType="User">
    select * from user
    <where>
        <foreach collection="ids" item="id" open="and id in (" close=")" separator=",">
             #{id}
        </foreach>
    </where>
</select>

7. SQL片段

  • 使用SQL标签抽取公共的部分

  • 在需要使用的地方使用Include标签引用即可

<sql id="userSql">
    <if test="name != null">
        and name = #{name}
    </if>
    <if test="pwd != null">
        and pwd = #{pwd}
    </if>
</sql>
<select id="queryUser" parameterType="map" resultType="User">
    select * from user 
    <where>
        <include refid="userSql"></include>
    </where>
</select>

10.分页

思考:为什么分页?

  • 减少数据的处理量

1. 使用Limit分页

<!--分页查询 
	SELECT * from user limit startIndex,pageSize
	SELECT  * from user limit 3 #[0,n]
 -->

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

2. RowBounds分页

<!-- Mapper.xml 分页2-->
<select id="getUserByRowBounds" resultMap="UserMap">
    select * from user
</select>
public void getUserByRowBounds(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    //RowBounds实现
    RowBounds rowBounds = new RowBounds(1, 2);
    //通过Java代码层面实现分页 null为where参数
    List<User> userList = sqlSession.selectList("com.dao.UserMapper.getUserByRowBounds", null, rowBounds);
    for (User user : userList) {
        System.out.println(user);
    }
    sqlSession.close();
}

11. 使用注解

1. 面向接口开发

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

2. 使用注解开发

  • 注解在接口上实现
@Select("select * from user")
List<User> getUsers();

//方法存在多个参数,所有参数前面必须加上@Param("id")注解
@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 = #{uid}")
int deleteUser(@Param("uid") int id);
  • 需要在核心配置文件中绑定接口
<mappers>
    <mapper class="com.dao.UserMapper"/>
</mappers>
  • 测试
@Test
public void getUsers(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    User users = mapper.getUserById(1);
    System.out.println(user);
    sqlSession.close();
}
  • @Param()注解
    • 基本类型的参数或者String类型,需要加上
    • SQL中引用的就是我们这里的@Param("")中设定的属性名!

12. 日志

1. 日志工厂 logImpl

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

2. STDOUT_LOGGING

(标准日志输出) 在mybatis-config.xml核心配置文件中配置日志!

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

3. Log4j

  • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
  • 我们也可以控制每一条日志的输出格式;
  • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
  • 可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
  1. 先在pom.xml文件中导入log4j的依赖包
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
  1. 在resources文件夹下建立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
  1. 在mybatis-config.xml核心配置文件中配置log4j为日志!
<settings>
    <setting name="logImpl" value="LOG4J"/>
</settings>
  1. 简单使用
//在要使用Log4j的测试类中,导入包
import org.apache.log4j.Logger;
//日志对象,参数为当前类的class
static Logger logger = Logger.getLogger(UserDaoTest.class);

//日志级别
logger.info("info:进入了testLog4j");
logger.debug("DEBUG:进入了testLog4j");
logger.error("erro:进入了testLog4j");

13. 缓存

1. 什么是缓存[Cache]?

  • 存在内存中的临时数据。
  • 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库查询文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。

2. 为什么使用缓存?

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

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

  • 经常查询并且不经常改变的数据。【可以使用缓存】

4. Mybatis缓存

  • Mybatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
  • Mybatis系统中默认定义了两级缓存:一级缓存和二级缓存
    • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
    • 二级缓存需要手动开启和配置,它是基于namespace级别的缓存。
      为了提高扩展性,Mybatis定义了缓存接口Cache,我们可以通过实现Cache接口来自定义二级缓存。

5. 一级缓存

  • 一级缓存也叫本地缓存:SqlSession
    • 与数据库同一次会话期间查询到的数据会放在本地缓存中
    • 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库
@Test
public void test1() {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    User user = mapper.getUserById(1);
    System.out.println(user);

    System.out.println("=====================================");

    User user2 =  mapper.getUserById(1);
    System.out.println(user2 == user);
}

在这里插入图片描述

缓存失效的情况:

  1. 查询不同的东西

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

  3. 查询不同的Mapper.xml

  4. 手动清理缓存

    sqlSession.clearCache();
    

6. 二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
  • 一级缓存默认开启(SqlSession级别的缓存,也称为本地缓存)
  • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
  • 为了提高可扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来定义二级缓存。
  1. 开启全局缓存
<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
  1. 在Mapper.xml中使用缓存
<!--在当前Mapper.xml中使用二级缓存-->
<cache eviction="FIFO"
       flushInterval="60000"
       size="512"
       readOnly="true"/>
  1. 实体类序列化
public class User implements Serializable{
}

7. 工作机制

  • 缓存查看顺序

    • 先查看二级缓存中有没有数据
    • 再看一级缓存中有没有数据
    • 查询数据库
  • 缓存保存顺序

    • 所有的数据都会放在一级缓存中
    • 只有当前会话提交,或者关闭的时候,才会提交到二级缓存中

8. 自定义缓存-ehcache

Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存。

目前:Redis数据库来做缓存!K-V

  • 导包
<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.2.1</version>
</dependency>
  • 在mapper中指定使用我们的ehcache缓存实现
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

14. Lombok

​ Lombok项目是一个Java库,它会自动插入编辑器和构建工具中,Lombok提供了一组有用的注释,用来消除Java类中的大量样板代码。仅五个字符(@Data)就可以替换数百行代码从而产生干净,简洁且易于维护的Java类。

  1. 导入lombok的jar包
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.10</version>
    <scope>provided</scope>
</dependency>
  1. 在实体类上加注解即可
@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	//Getter  @Setter
@AllArgsConstructor //有参构造
@NoArgsConstructor	//无参构造
@ToString			//toString
public class User{
}

【狂神说】Mybatis最新完整教程IDEA版参考链接:https://www.bilibili.com/video/BV1NE411Q7Nx
文章参考:https://mybatis.org/mybatis-3/zh/index.html

标签:缓存,name,基础,log4j,user,Mybatis,id,select
来源: https://blog.csdn.net/qq_26855187/article/details/120354717

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有