当前位置:   article > 正文

SSM框架_Mybatis_mybatis3.5.9的pom

mybatis3.5.9的pom

SSM框架_Mybatis

中文帮助文档:https://mybatis.org/mybatis-3/zh/index.html

1、简介

什么是Mybatis?

  • MyBatis 是一款优秀的持久层框架
  • 它支持自定义 SQL、存储过程以及高级映射
  • MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
  • MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
  • MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。
  • 2013年11月迁移到Github。

如何获得Mybatis?

  • maven仓库:
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.9</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • GitHub:https://github.com/mybatis/mybatis-3/releases

持久化

数据持久化

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

为什么需要持久化?

  • 有一些对象不能丢失

  • 内存太贵

持久层

Dao层、Service层、Controller层

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

为什么需要Mybatis?

  • 帮助程序员将数据存储到数据库中
  • 方便
  • 传统的JDBC代码太复杂
  • 不用Mybatis也可以,只是框架更容易上手
  • 简单易学
  • 灵活
  • sql和代码的分离,提高了可维护性。
  • 提供映射标签,支持对象与数据库的orm字段关系映射
  • 提供对象关系映射标签,支持对象关系组建维护
  • 提供xml标签,支持编写动态sql。
  • 最重要的一点:使用的人多

2、创建MyBatis程序

思路:搭建环境-导入Mybatis-编写代码-测试

  • 创建好数据库

  • 创建一个普通的maven项目,删除src目录,把他当做父工程

- 父项目导入依赖,子项目可以直接使用:

<dependencies>
    <!-- mysql驱动-->
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.27</version>
    </dependency>
    <!-- mybatis-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.9</version>
    </dependency>
    <!-- Junit-->
    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
    </dependency>
</dependencies>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 再建一个模块(也就是子工程)

- 编写mybatis核心配置文件(在resource目录下新建文件:mybatis-config.xml)

<?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.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT&amp;useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
</configuration>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

- 编写mybatis工具类:

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            String resources = "mybatis-config.xml";
            InputStream is = Resources.getResourceAsStream(resources);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

- 编写 Dao接口/Mapper接口,XXXmapper.xml文件

<?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">

<!-- namespace命名空间会绑定一个 Dao接口/Mapper接口,mapper要在mybatis配置文件中注册-->
<mapper namespace="com.dl.dao.UserDao">
    <!--查询语句:id对应方法 -->
    <select id="getUserList" resultType="com.dl.pojo.User">
        SELECT * FROM mybatis.user;
    </select>
</mapper>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

- 解决找不到mapper文件:在pom.xml中加入如下代码

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

-单元测试

@Test
public void test(){
    // 获得SQLSession对象
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    try {
        // 方式一:getMapper
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> userList = mapper.getUserList();
        // 方式二:
        //List<User> userList = sqlSession.selectList("com.dl.dao.UserDao.getUserList");
        //遍历
        for (User user : userList) {
            System.out.println(user);
        }
    }catch (Exception e){
        e.printStackTrace();
    }finally {
        sqlSession.close(); //sqlSession要在finally中关闭,所以手动加 try-catch
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

3、CRUD

注意:增删改需要提交事务

接口:

package com.dl.dao;
import com.dl.pojo.User;
import java.util.List;
public interface UserDao {

    //查询全部
    List<User> getUserList();

    //根据id查
    User getUserById(int id);

    //insert一个用户
    int addUser(User user);

    //修改用户
    int updateUser(User user);

    //删除用户
    int deleteUser(int id);

    
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

UserMapper.xml:

<?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">

<!-- namespace命名空间会绑定一个 Dao接口/Mapper接口,mapper要在mybatis配置文件中注册-->
<mapper namespace="com.dl.dao.UserDao">
    <!--查询语句:id对应方法  resultType:SQL语句执行的返回值 -->
    <select id="getUserList" resultType="com.dl.pojo.User">
        SELECT * FROM mybatis.user;
    </select>

    <!--  parameterType:参数类型   #{方法的形参} -->
    <select id="getUserById" resultType="com.dl.pojo.User" parameterType="int">
        select * from mybatis.user where id = #{id};
    </select>

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

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

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

</mapper>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

单元测试:

注意:增删改需要提交事务

package com.dl.dao;

import com.dl.pojo.User;
import com.dl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;

public class UserDaoTest {

    @Test
    public void test(){
        // 获得SQLSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try {
            // 方式一:getMapper
            UserDao mapper = sqlSession.getMapper(UserDao.class);
            List<User> userList = mapper.getUserList();
            // 方式二:
            //List<User> userList = sqlSession.selectList("com.dl.dao.UserDao.getUserList");
            //遍历
            for (User user : userList) {
                System.out.println(user);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close(); //sqlSession要在finally中关闭,所以手动加 try-catch
        }
    }

    @Test
    public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        User user = mapper.getUserById(1);
        System.out.println(user);
        sqlSession.close();
    }

    //增删改需要提交事务
    @Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        int row = mapper.addUser(new User(4, "小白", "123456"));
        if(row > 0){
            System.out.println("插入成功!");
        }
        //提交事务,不提交则插入不成功
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void updateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        int row = mapper.updateUser(new User(4, "xiaobai", "111111"));
        if (row > 0){
            System.out.println("修改成功!");
        }
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void deleteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        int row = mapper.deleteUser(4);
        if (row > 0){
            System.out.println("删除成功!");
        }
        sqlSession.commit();
        sqlSession.close();
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79

万能Map:

假设我们的实体类,数据库中的表、字段或者参数过多,我们应当考虑使用Map

int addUser2(Map<String,Object> map);
  • 1
<!--  参数类型为 map  ,参数对应的是map的key   -->
<insert id="addUser2" parameterType="map">
    insert into mybatis.user (id,name,pwd) values (#{userId},#{userName },#{pwd});
</insert>
  • 1
  • 2
  • 3
  • 4
@Test
public void addUser2(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("userId",6);
    map.put("userName","测试map");
    map.put("pwd","111111");
    int row = mapper.addUser2(map);
    if(row > 0){
        System.out.println("插入成功!");
    }
    //提交事务,不提交则插入不成功
    sqlSession.commit();
    sqlSession.close();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

传参:

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

4、配置解析

<?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>
    <!--   -->
    <properties resource="db.properties" />

    <!--  类型别名一: -->
<!--    <typeAliases>-->
<!--        <typeAlias type="com.dl.pojo.User" alias="User" />-->
<!--    </typeAliases>-->
    
    <!--  类型别名二:  name:包名  ,如果没加注解那么别名为小写的类名;加了注解就是注解定义的名字:@Alias("User") -->
    <typeAliases>
        <package name="com.dl.pojo"></package>
    </typeAliases>

    <environments default="test">
        <environment id="development">
            <!-- 事务管理:JDBC 和 Managed 两种-->
            <transactionManager type="JDBC"/>
            <!-- 数据源类型 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT&amp;useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
        <!-- 可以配置多套环境 -->
        <environment id="test">
            <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>

    <!--  映射器:  -->
    <mappers>
        <!-- 方式一: -->
        <!-- 使用相对于类路径的资源引用
            <mapper resource="com/dl/dao/UserMapper.xml"/>
        -->
        <mapper resource="com/dl/dao/UserMapper.xml"/>

        <!-- 方式二: -->
        <!--  使用映射器接口实现类的完全限定类名
            接口和mapper配置文件必须同名
            接口和mapper配置文件必须在同一个包下
            <mapper class="com.dl.dao.UserMapper"/>
         -->

        <!-- 方式三: -->
        <!-- 将包内的映射器接口实现全部注册为映射器
            接口和mapper配置文件必须同名
            接口和mapper配置文件必须在同一个包下
            <package name="com.dl.dao"/>
        -->
    </mappers>
    
</configuration>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68

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

解决方法一:利用 as 起别名

//  select * from mybatis.user where id = #{id}

//  select id,name,pwd from mybatis.uer where id  =#{id}

//  select id,name,pwd as password from mybatis.uer where id  =#{id}
  • 1
  • 2
  • 3
  • 4
  • 5

解决方法二:resultMap结果集映射

id name pwd
id name password
  • 1
  • 2
<!--结果集映射-->
<!-- type:类型 -->
<resultMap id="UserMap" type="User">
    <!--column 数据库中的字段 property 实体类中的属性-->
    <result column="pwd" property="password"></result>
</resultMap>
<!--  resultMap绑定上面的id -->
<select id = "getUserById" resultMap="UserMap">
        select * from mybatis.user where id = #{id}
</select>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • resultMap 元素是 MyBatis 中最重要最强大的元素

  • 对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了。

  • ResultMap 最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们,(只需要显示的映射名字不同的字段)

6、日志

如果数据库操作出现了异常,日志可以很好的排错

mybatis核心配置文件中------>setting------->logImpl:指定 MyBatis 所用日志的具体实现,未指定时将自动查找。

日志工厂:

  • SLF4J
  • LOG4J 【掌握】
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING 【掌握】
  • NO_LOGGING
logImpl指定 MyBatis 所用日志的具体实现,未指定时将自动查找。SLF4J | LOG4J(deprecated since 3.5.9) | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING未设置

标准的日志工厂实现:STDOUT_LOGGING

<!-- settings  -->
<settings>
    <!-- 指定 MyBatis 所用日志的具体实现,注意大小写,冒号前后不能加空格  -->
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
  • 1
  • 2
  • 3
  • 4
  • 5

LOG4J

什么是LOG4J?

  • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等
  • 我们也可以控制每一条日志的输出格式;
  • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
  • 最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
1、导包:
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
2、创建log4j.propertise

log4j.propertise 代码:

#将等级为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/dl.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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

log4j.propertise 配置详解:

##logger是进行记录的主要类,appender是记录的方式,layout是记录的格式
#Logger - 日志写出器,供程序员输出日志信息 
#Appender - 日志目的地,把格式化好的日志信息输出到指定的地方去 
#ConsoleAppender - 目的地为控制台的Appender 
#FileAppender - 目的地为文件的Appender 
#RollingFileAppender - 目的地为大小受限的文件的Appender 
#Layout - 日志格式化器,用来把程序员的logging request格式化成字符串 
#PatternLayout - 用指定的pattern格式化logging request的Layou

#Log4j提供的appender有以下几种:
#  org.apache.log4j.ConsoleAppender(控制台),
#  org.apache.log4j.FileAppender(文件),
#  org.apache.log4j.DailyRollingFileAppender(每天产生一个日志文件),
#  org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件),
#  org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方)

#Log4j提供的layout有以下几种:
#  org.apache.log4j.HTMLLayout(以HTML表格形式布局),
#  org.apache.log4j.PatternLayout(可以灵活地指定布局模式),
#  org.apache.log4j.SimpleLayout(包含日志信息的级别和信息字符串),
#  org.apache.log4j.TTCCLayout(包含日志产生的时间、线程、类别等等信息)

#Log4J采用类似C语言中的printf函数的打印格式格式化日志信息,打印参数如下
#    %m 输出代码中指定的消息
#    %M 输出日志发生的方法名
#  %p 输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL
#  %r 输出自应用启动到输出该log信息耗费的毫秒数
#  %c 输出所属的类目,通常就是所在类的全名
#  %t 输出产生该日志事件的线程名
#  %n 输出一个回车换行符,Windows平台为“rn”,Unix平台为“n”
#  %d 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,比如:%d{yyyy MMM dd HH:mm:ss,SSS},输出类似:2002年10月18日 22:10:28,921
#  %l 输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数。举例:Testlog4.main(TestLog4.java:10)
#    %L 输出日志发生的位置
#     %F 输出类名


#####################################################################
#设置级别和目的地 -- 把日志等级为debug的日志信息输出到stdout和SYS,QUERY这三个目的地
log4j.rootLogger=debug,STDOUT
# stdout:目的地 -- 打印到屏幕
## org.apache.log4j.ConsoleAppender:控制台
log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
## org.apache.log4j.PatternLayout:灵活地指定布局模式
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
## 上一句设置了PatternLayout灵活指定格式,则要指定打印参数 [%-5p][%d{HH:mm:ss}][%c-%M] %m%n   [%-5p][%d{HH:mm:ss}][%l] %m%n
log4j.appender.STDOUT.layout.ConversionPattern=[%-5p][%d{yyyy-MM-dd HH:mm:ss sss}][%t][%c-%M][%L](%F:%L) - %m%n


# QUERY:目的地 -- 输出到文件(限定每个文件大小)
## 凡是 info、warn、error、fatal 级别的数据都会在这里执行输出到 query.log 日志文件中
##log4j.logger.QUERY=INFO,QUERY
log4j.logger.QUERY=INFO
##输出到文件(这里默认为追加方式),使用org.apache.log4j.FileAppender:日志会在一个文件中追加
log4j.appender.QUERY=org.apache.log4j.RollingFileAppender
##设置文件输出路径;html:log/query.html
log4j.appender.QUERY.File=log/query.log
##设置文件输出样式;html格式: org.apache.log4j.HTMLLayout
log4j.appender.QUERY.layout=org.apache.log4j.PatternLayout
## 上一句设置了PatternLayout灵活指定格式,则要指定打印参数 [%-5p][%d{HH:mm:ss}][%l] %m%n
log4j.appender.QUERY.layout.ConversionPattern=[%-5p][%d{yyyy-MM-dd HH:mm:ss}][%c-%M] %m%n
## 指定文件的最大 大小
log4j.appender.QUERY.MaxFileSize=2048KB
## 可被备份的日志数
log4j.appender.QUERY.MaxBackupIndex=100


# SYS:目的地 -- 输出到文件(每天产生一个文件) 
## 凡是 error、fatal 级别的数据都会在这里执行输出到 sys.log 日志文件中
#log4j.logger.SYS=error,SYS
log4j.logger.SYS=error
## org.apache.log4j.RollingFileAppender:每天产生一个日志文件
#使用org.apache.log4j.FileAppender:日志会在一个文件中追加
log4j.appender.SYS=org.apache.log4j.DailyRollingFileAppender
##设置文件输出路径 ${user.home}/log/sys.log
log4j.appender.SYS.File=log/sys.log
## org.apache.log4j.PatternLayout:灵活地指定布局模式
log4j.appender.SYS.layout=org.apache.log4j.PatternLayout
## 上一句设置了PatternLayout灵活指定格式,则要指定打印参数 [%-5p][%d{HH:mm:ss}][%l] %m%n
log4j.appender.SYS.layout.ConversionPattern=[%-5p][%d{HH:mm:ss}][%C-%M] %m%n

#设置特定包的级别
##com.swh.weixin包下的日志内容显示级别为debug,和目的地
## 把com.swh.weixin.util包下日志等级为debug的信息输出到pack 目的地
#log4j.logger.com.swh.weixin.util=debug,pack
##输出到文件(这里默认为追加方式),使用org.apache.log4j.FileAppender:日志会在一个文件中追加
log4j.appender.pack=org.apache.log4j.RollingFileAppender
##设置文件输出路径  或者 ${user.home}/log/pack.log
log4j.appender.pack.File=log/pack.log
##设置文件输出样式
log4j.appender.pack.layout=org.apache.log4j.PatternLayout
## 上一句设置了PatternLayout灵活指定格式,则要指定打印参数 [%-5p][%d{HH:mm:ss}][%l] %m%n
log4j.appender.pack.layout.ConversionPattern=[%-5p][%d{yyyy MM dd HH:mm:ss}][%c-%M] %m%n
## 指定文件的最大 大小
log4j.appender.pack.MaxFileSize=1024KB
#日志最大备份数目
log4j.appender.pack.MaxBackupIndex=100

########################################################################
##设置级别和目的地  
#log4j.rootLogger=debug,appender1,appender2  
##只设置特定包的级别和目的地
#log4j.logger.com.coderdream=debug,appender1
#log4j.logger.com.coderdream.Dao=info,appender1,appender2

##输出到控制台
#log4j.appender.appender1=org.apache.log4j.ConsoleAppender
##设置输出样式
#log4j.appender.appender1.layout=org.apache.log4j.PatternLayout
##自定义样式
## %r 时间 0
## %t 方法名 main
## %p 优先级 DEBUG/INFO/ERROR
## %c 所属类的全名(包括包名)
## %l 发生的位置,在某个类的某行
## %m 输出代码中指定的讯息,如log(message)中的message
## %n 输出一个换行符号
#log4j.appender.appender1.layout.ConversionPattern=[%d{yy/MM/dd HH:mm:ss:SSS}][%C-%M] %m%n

##输出到文件(这里默认为追加方式)
#log4j.appender.appender2=org.apache.log4j.FileAppender
##设置文件输出路径
##【1】文本文件
#log4j.appender.appender2.File=c:/Log4JCRM_Dao.log
##设置文件输出样式
#log4j.appender.appender2.layout=org.apache.log4j.PatternLayout
#log4j.appender.appender2.layout.ConversionPattern=[%d{HH:mm:ss:SSS}][%C-%M] -%m%n


##把日志文件写入数据库
##########################日志输出到远程数据库########################################
##把日志文件写入数据库
##记录的日志级别
log4j.logger.db=info
##日志输出到数据库
log4j.appender.db = org.apache.log4j.jdbc.JDBCAppender
##缓存
log4j.appender.db.BufferSize = 0
##数据库驱动
log4j.appender.db.Driver = com.mysql.jdbc.Driver
##数据url地址 ,本地可简写:jdbc:mysql:///test
log4j.appender.db.URL = jdbc:mysql://localhost:3306/swh_hibernate4?useUnicode=true&characterEncoding=utf8
##数据库用户名
log4j.appender.db.User = root
##数据库密码
log4j.appender.db.Password = root
##日志布局模式
log4j.appender.db.layout = org.apache.log4j.PatternLayout
##日志插入数据库中,t_logs 表字段可自定义
log4j.appender.db.layout.ConversionPattern = INSERT INTO t_logs(createDate, thread, priority, category,<br />
methodName, message) values('%d', '%t', '%-5p', '%c','%M', '[%l]-%m')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
3.配置log4j为日志的实现:
<settings>
    <!--指定 MyBatis所用日志的具体实现为 LOG4J ,注意大小写,冒号前后不能加空格  -->
    <setting name="logImpl" value="LOG4J"/>
</settings>
  • 1
  • 2
  • 3
  • 4
简单使用
  • 在要使用Log4j的类中导入 import org.apache.log4j.Logger;

  • 生成一个日志对象,参数为当前类的class

  • static Logger logger = Logger.getLogger(UserDaoTest.class); //UserDaoTest为相关的类

import org.apache.log4j.Logger;
import org.junit.Test;

public class UserDaoTest {
    static Logger logger = Logger.getLogger(UserDaoTest.class);
    @Test
    public void testLog4j(){
        // 日志级别:
        logger.info("info:进入了log4j");
        logger.debug("debug:进入了log4j");
        logger.error("error:进入了log4j");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

7、分页

减少数据的处理量

1.使用limit分页

SELECT * from user limit startIndex,pagesize; # 从startIndex开始,每页显示pagesize个
SELECT * from user limit 3;   # 0,3
  • 1
  • 2

代码:

//使用sql分页
List<User> getLimit(Map<String,Integer> map);
  • 1
  • 2
<select id="getLimit" resultType="user" parameterType="map">
    select * from user limit #{startIndex},#{pageSize};
</select>
  • 1
  • 2
  • 3
@Test
public void getLimit(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("startIndex",0);
    map.put("pageSize",2);
    List<User> list = mapper.getLimit(map);
    for (User user : list) {
        System.out.println(user);
    }
    sqlSession.close();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

2.使用RowBounds类分页

代码:

//使用RoeBounds类分页
List<User> getLimit2();
  • 1
  • 2
<!--  分页2 -->
<select id="getLimit2" resultType="user">
    select * from user ;
</select>
  • 1
  • 2
  • 3
  • 4
@Test
public void testLimit2(){
    //创建分页对象 从0开始,每页2条数据
    RowBounds rowBounds = new RowBounds(0, 2);
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    List<User> list = sqlSession.selectList("com.dl.dao.UserMapper.getLimit2",null,rowBounds);
    for (User user : list) {
        System.out.println(user);
    }
    sqlSession.close();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

3、前端插件分页:

MyBatis 分页插件:https://pagehelper.github.io/

8、使用注解开发

1.面向接口编程

大家之前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程
根本原因:解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得更容易,规范性更好
在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;而各个对象之前的协作关系则成为系统设计的关键,小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容,面向接口编程就是指按照这种思想来编程。

关于接口的理解

接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离)的分离。

接口的本身反映了系统设计人员对系统的抽象理解。

接口应有两类:

  • 第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class);
  • 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface);

一个体有可能有多个抽象面,抽象体与抽象面是有区别的

三个面向区别

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

2.使用注解完成CRUD

使用注解来映射简单语句会使代码显得更加简洁,然而对于稍微复杂一点的语句,Java 注解就力不从心了,并且会显得更加混乱。 因此,如果你需要完成很复杂的事情,那么最好使用 XML 来映射语句。

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

public static SqlSession getSqlSession(){
    // return sqlSessionFactory.openSession();
    return sqlSessionFactory.openSession(true); //开启事务自动提交,我,我们就不用手动提交事务了
}
  • 1
  • 2
  • 3
  • 4

关于@param注解

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型的话,可以忽略,但是建议都加上
  • 我们在SQL中引用的就是我们在@Param("")中设定的东西

1.注解在接口上实现

import org.apache.ibatis.annotations.*;
import java.util.List;

public interface UserMapper {

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

    //当传递多个参数值时,使用 @Param("")注解
    @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 addUser(User user);

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

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

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

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

<mappers>
    <mapper class="com.dl.dao.UserMapper"></mapper>
</mappers>
  • 1
  • 2
  • 3

3、Mybatis详细的执行流程!

在这里插入图片描述

9.Lombok

Project Lombok是一个java库,它可以自动插入编辑器和构建工具,使java更加丰富多彩。永远不要再编写另一个getter或equals方法,使用一个注释,你的类就有了一个功能齐全的构建器,自动化你的日志变量,等等。

使用步骤:

1.在IDEA中安装Lombok插件

2.在项目中导入jar包

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.22</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3.在实体类上加注解即可

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
    private int id;
    private String name;
    private String pwd;
    
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

注解:

  • @Data:无参构造,get、set、toString、hashcode、equals
  • @AllArgsConstructor:有参构造
  • @NoArgsConstructor:无参构造
  • @ToString:重写ToString方法

10、多对一

复杂的属性映射,需要单独处理:association处理对象 ,collection处理集合

环境搭建

CREATE TABLE `teacher` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT INTO teacher(`id`, `name`) VALUES (1, ' 秦老师'); 

CREATE TABLE `student` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  `tid` INT(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fktid` (`tid`),
  CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 

INSERT INTO `student` (`id`, `name`, `tid`) VALUES (1,' 小明', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (2, '小红', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (3, '小张', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (4, '小李', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (5, '小王', 1);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    private int id;
    private String name;
    private Teacher teacher;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Teacher {
    private int id;
    private String name;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 多个学生对应一个老师
  • 对于学生而言,关联…多个学生关联一个老师【多对一】
  • 对于老师而言,集合,一个老师有很多学生【一对多】
  • 关联了一个外键

结果映射(resultMap)

复杂的属性映射,需要单独处理:association处理对象 ,collection处理集合

  • association

    • 一个复杂类型的关联;许多结果将包装成这种类型

    • 嵌套结果映射 – 关联可以是 resultMap 元素,或是对其它结果映射的引用

  • collection

    • 一个复杂类型的集合

    • 嵌套结果映射 – 集合可以是 resultMap 元素,或是对其它结果映射的引用

ResultMap 的属性列表:

属性描述
id当前命名空间中的一个唯一标识,用于标识一个结果映射。
type类的完全限定名, 或者一个类型别名(关于内置的类型别名,可以参考上面的表格)。
autoMapping如果设置这个属性,MyBatis 将会为本结果映射开启或者关闭自动映射。 这个属性会覆盖全局的属性 autoMappingBehavior。默认值:未设置(unset)。

方式一:关联的嵌套 Select 查询

通过association嵌套select

<!--  复杂的属性映射,需要单独处理:association处理对象 ,collection处理集合 -->

<select id="getStudent" resultMap="getStudentAndTeacher">
    select * from student ;
</select>
<resultMap id="getStudentAndTeacher" type="Student">
    <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
    select * from teacher where id = #{tid} ;
</select>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

方式二:关联的嵌套结果映射

通过association嵌套result

<select id="getStudent2" resultMap="getStudentAndTeacher2">
    select student.id sid,student.`name` sname,teacher.`name` tname
    from student,teacher
    where student.tid=teacher.id;
</select>
<resultMap id="getStudentAndTeacher2" type="Student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <association property="teacher" javaType="Teacher">
        <result property="name" column="tname" />
    </association>
</resultMap>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

11、一对多

  • 对于老师来说就是一对多
  • 使用collection处理集合

环境搭建

数据库不变和上面一样

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    private int id;
    private String name;
    private int tid;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Teacher {
    private int id;
    private String name;
    private List<Student> students;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

方式一:关联的嵌套结果映射

通过collection嵌套result

<select id="getTeacher" resultMap="getTeacher">
    select student.id sid,student.`name` sname, teacher.id tid,teacher.`name` tname
    from student,teacher
    where student.tid=teacher.id and teacher.id = #{id};
</select>
<resultMap id="getTeacher" type="Teacher">
    <result property="name" column="tname"/>
    <result property="id" column="tid" />
    <collection property="students" ofType="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

方式二:关联的嵌套 Select 查询

通过collection嵌套select

<select id="getTeacher2" resultMap="getTeacher22">
    select * from teacher where id = #{id};
</select>
<resultMap id="getTeacher22" type="Teacher">
    <result property="id" column="id"/>
    <collection property="students" javaType="ArrayList" ofType="Student" column="id" select="getStudent22"/>
</resultMap>
<select id="getStudent22" resultType="Student">
    select * from student where tid = #{id} ;
</select>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

总结

说到底,一对多和多对一就是在利用resultMap处理对象和集合的映射

association用来处理对象的映射

collection用来处理集合的映射

12、动态SQL

什么是动态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
  • 4
  • 5
  • 6
  • 7

添加数据:

public interface BlogMapper {
    //添加数据
    int addBlog(Blog blog);
}
  • 1
  • 2
  • 3
  • 4
<insert id="addBlog" parameterType="Blog">
    insert into blog (id,title,author,create_time,views) values (#{id}, #{title}, #{author}, #{createTime}, #{views});
</insert>
  • 1
  • 2
  • 3
@org.junit.Test
public void addBlog(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    Blog blog = new Blog();
    blog.setId(IdUtils.getId());
    blog.setTitle("mybatis学习笔记");
    blog.setAuthor("小白");
    blog.setCreateTime(new Date());
    blog.setViews(9999);
    //插入第一条数据
    mapper.addBlog(blog);
    //插入第二条数据
    blog.setId(IdUtils.getId());
    blog.setTitle("spring学习笔记");
    mapper.addBlog(blog);
    //插入第三条数据
    blog.setId(IdUtils.getId());
    blog.setTitle("springMVC学习笔记");
    mapper.addBlog(blog);
    sqlSession.close();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

if

//查询
List<Blog> queryBlog(Map map);
  • 1
  • 2
<select id="queryBlog" 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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
@org.junit.Test
public void queryBlog(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    Map map = new HashMap();
    map.put("title","mybatis学习笔记");
    List<Blog> blogs = mapper.queryBlog(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    sqlSession.close();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

choose、when、otherwise

只能匹配一个when

<select id="queryBlogChoose" 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 > 5000
            </otherwise>
        </choose>
    </where>
</select>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

trim(where,set)

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


set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号

<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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

如果if都不满足会报错,此时的SQL: update blog where id = #{id}


可以通过自定义 trim 元素来定制 where 元素的功能,比如,和 where 元素等价的自定义 trim 元素为:

<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>
  • 1
  • 2
  • 3

prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。上述例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容。

set 元素等价的自定义 trim 元素:

<trim prefix="SET" suffixOverrides=",">
  ...
</trim>
  • 1
  • 2
  • 3

注意,我们覆盖了后缀值设置,并且自定义了前缀值。

SQL片段

有的时候我们会将一些公共的部分提取出来,方便复用。

  • 使用sql标签抽取出公共的部分
  • 在需要使用的地方使用include标签引用
<!--  这是提取出来的公共部分,给个id方便引用  -->
<sql id="if-title-author">
    <if test="title != null">
        title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
</sql>
<select id="queryBlog" parameterType="map" resultType="Blog">
    select * from blog
    <where>
<!-- 这里引用通过refid引用的代码片段 -->   
        <include refid="if-title-author"></include>
    </where>
</select>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

注意事项:

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

foreach

foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符

可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

-- 查询1~3号的信息:
select * from blog where 1=1 and (id = 1 or id = 2 or id = 3);
  • 1
  • 2
//查询1~3号的博客
List<Blog> queryBlogForeach(Map map);
  • 1
  • 2
<!-- select * from blog where 1=1 and (id = 1 or id = 2 or id = 3); -->
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
    select * from blog
    <where>
        <foreach collection="list" item="id" open="and (" close=")" separator="or">
            id=#{id}
        </foreach>
    </where>
</select>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
@org.junit.Test
public void queryBlogForeach(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    Map map = new HashMap();
    
    ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(2);
    list.add(3);
    map.put("list",list);

    List<Blog> blogs = mapper.queryBlogForeach(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    sqlSession.close();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

13、缓存

简介

查询:连接数据,耗资源!
一次查询的结果,给他暂存在一个可以取到的地方! ---> 内存 : 缓存

我们再次查询相同数据的时候,直接走缓存,就不用走数据库了。

  • 1
  • 2
  • 3
  • 4
  • 5

什么是缓存[Cache]?

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

为什么使用缓存?

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

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

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

Mybatis缓存

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

Mybatis系统默认定义了两级缓存:一级缓存二级缓存

  • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称本地缓存

  • 二级缓存需要手动开启和配置,它是基于namespace级别的缓存(一个namespace绑定了一个Mapper接口

  • 为了提高扩展性,Mybatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存

一级缓存

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

  • 与数据库同一次会话期间查询到的数据会放在本地缓存中

  • 以后如果需要获取相同的数据,直接从缓存中拿,没有必要再去查询数据库

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

测试:

开启日志:

<settings>
    <!-- 开启日志 -->
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
  • 1
  • 2
  • 3
  • 4

测试在一个Session中查询两次相同记录!

@Test
public void getUserById(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    //第一次查
    User user1 = mapper.getUserById(1);
    //第二次查
    User user2 = mapper.getUserById(1);
    System.out.println(user1 == user2); //true 比较的是地址值
    sqlSession.close();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

截取日志信息:

Opening JDBC Connection
Created connection 671046933.
==>  Preparing: select * from user where id = ?;
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd
<==        Row: 1, 张三, 111111
<==      Total: 1
true
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@27ff5d15]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

发现尽管调用了两次方法,但SQL只执行了一次,第二次的数据是从缓存在取的

  • 映射语句文件中的所有 select 语句的结果将会被缓存。
  • 映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
  • 缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
  • 缓存不会定时进行刷新(也就是说,没有刷新间隔)。
  • 缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
  • 缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
缓存失效:
  • 不同sqlSession对象
  • 查询不同的数据
  • 增删改可能使数据发生变化,所以必定会刷新(清空)缓存
    @Test
    public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user1 = mapper.getUserById(1);
        int i = mapper.updateUser(new User(2, "缓存刷新", "666666"));
        User user2 = mapper.getUserById(1);
        System.out.println(user1 == user2);
        sqlSession.close();
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
Opening JDBC Connection
Created connection 671046933.
==>  Preparing: select * from user where id = ?;
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd
<==        Row: 1, 张三, 111111
<==      Total: 1
==>  Preparing: update user set name = ? , pwd = ? where id = ?;
==> Parameters: 缓存刷新(String), 666666(String), 2(Integer)
<==    Updates: 1
==>  Preparing: select * from user where id = ?;
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd
<==        Row: 1, 张三, 111111
<==      Total: 1
false
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@27ff5d15]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 手动清理缓存
sqlSession.clearCache();
  • 1
小结
  • 一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个阶段有效

  • 一级缓存就是一个map

二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用于太低,所以诞生了二级缓存;
  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存;

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

要启用全局的二级缓存,只需要在你的 SQL 映射文件(xxxxxMapper.xml)中添加一行:

<cache/>
  • 1
清除策略有:
  • LRU – 最近最少使用:移除最长时间不被使用的对象。
  • FIFO – 先进先出:按对象进入缓存的顺序来移除它们。
  • SOFT – 软引用:基于垃圾回收器状态和软引用规则移除对象。
  • WEAK – 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。
步骤:

1、在核心配置文件中,显示的开启全局缓存,虽然默认就是开启的,增加代码的可读性

<!--   显示的开启全局缓存,默认就是开启的     -->
<setting name="cacheEnabled" value="true"/>
  • 1
  • 2

2、在SQL 映射文件(xxxxxMapper.xml)中添加:

<cache/>
  • 1

或者自定义配置属性:

<cache
  eviction="FIFO"
  flushInterval="60000"
  size="512"
  readOnly="true"
/>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。

3、测试

  • 实体类要序列化
  • 所有的数据都会先存在一级缓存中,只有当回话提交,或者关闭的时候才会提交到二级缓存中
@Test
public void getUserById(){
    SqlSession sqlSession1 = MybatisUtils.getSqlSession();
    SqlSession sqlSession2 = MybatisUtils.getSqlSession();
    UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
    UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
    User user1 = mapper1.getUserById(1);
    sqlSession1.close(); // 关闭一级缓存,才会提交到二级缓存

    User user2 = mapper2.getUserById(1);
    System.out.println(user1 == user2);
    sqlSession2.close();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

只会执行一次sql,第二次的查询是从二级缓存中取的

缓存机制

在这里插入图片描述

自定义缓存EhCache

  • EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。
  • Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器

1、导入jar包

<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.2.1</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2、在xxxMapper.xml中使用自定义缓存

<!--  自定义缓存:EhcacheCache  -->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
  • 1
  • 2

3、在resources目录下新建ehcache的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">

    <!-- 磁盘缓存位置 -->
    <diskStore path="java.io.tmpdir/ehcache"/>

    <!-- 默认缓存 -->
    <defaultCache
            maxEntriesLocalHeap="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxEntriesLocalDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>

    <!-- helloworld缓存 -->
    <cache name="HelloWorldCache"
           maxElementsInMemory="1000"
           eternal="false"
           timeToIdleSeconds="5"
           timeToLiveSeconds="5"
           overflowToDisk="false"
           memoryStoreEvictionPolicy="LRU"/>
</ehcache>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
<?xml version="1.0" encoding="UTF8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <!--
        diskStore :为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置,参数解释如下:
            user.hoeme - 用户主目录
            user.dir -  用户当前工作目录
            javaio.tmpdir - 默认临时文件
    -->
    <diskStore path="./tmpdir/Tmp_EhCache/">

    <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"/>
</ehcache>
        <!--
            defaultCache:默认缓存策略,当cache找不到定义的缓存时,则使用这个缓存策略,只能定义一个
        -->
        <!--
           name:缓存名称。
           maxElementsInMemory:缓存最大个数。
           eternal:对象是否永久有效,一但设置了,timeout将不起作用。
           timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
           timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
           overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。当系统宕机的时候是否保存到硬盘中
           diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
           maxElementsOnDisk:硬盘最大缓存个数。
           diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
           diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
           memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
           clearOnFlush:内存数量最大时是否清除。
        -->
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/872828
推荐阅读
相关标签
  

闽ICP备14008679号