【Java学习总结】MyBatis小结

一、概述

1.什么是MyBatis?

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

2.安装

要使用 MyBatis, 只需将 mybatis-x.x.x.jar 文件置于类路径(classpath)中即可。
如果使用 Maven 来构建项目,则需将下面的依赖代码置于 pom.xml 文件中。

<dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis</artifactId>
	<version>x.x.x</version>
</dependency>

3.为什么要使用MyBatis?

  1. 帮助开发人员将数据存入到数据库中。
  2. 方便:传统的JDBC代码太复杂了。MyBatis更加简化、自动化。
  3. 不用MyBatis也可以。使用MyBatis更容易上手。技术没有高低之分
  4. MyBatis优点:
    (1)简单易学
    (2)灵活
    (3)sql和代码的分离,提高了可维护性。
    (4)提供映射标签,支持对象与数据库的orm字段关系映射
    (5)提供对象关系映射标签,支持对象关系组建维护
    (6)提供xml标签,支持编写动态sql
  5. 最重要的一点:使用的人多

4.第一个MyBatis程序

  1. 搭建数据库
CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE TABLE `user`(
  `id` INT(20) NOT NULL PRIMARY KEY,
  `name` VARCHAR(30) DEFAULT NULL,
  `pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO `user`(`id`,`name`,`pwd`) VALUES
(1,'狂神','123456'),
(2,'张三','123456'),
(3,'李四','123890');
  1. 在Maven项目中导入依赖
    <!--导入依赖-->
    <dependencies>
        <!--MySQL驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!--Mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <!--Junit单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
  1. 编写数据库连接配置文件db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8
username=root
password=121314
  1. 编写MyBatis的核心配置文件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>

    <!--引入外部配置文件-->
    <properties resource="db.properties"/>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
</configuration>
  1. 编写MyBatis工具类MybatisUtils
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //使用Mybatis的第一步:获取sqlSessionFactory对象
            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();
    }
}
  1. 编写pojo实体类
//实体类
public class User {
    private int id;
    private String name;
    private String pwd;

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}
  1. 创建Mapper接口
public interface UserMapper {
	List<User> getUserList();
}
  1. 编写Mapper配置文件(接口实现类由原来的UserDaoImpl转变为一个 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">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.carry.dao.UserMapper">

    <!--select查询语句-->
    <select id="getUserList" resultType="com.carry.pojo.User">
        select * from mybatis.user
    </select>

</mapper>
  1. 在Mybatis核心配置文件中注册Mapper.XML
    <!--每一个Mapper.XML都需要在Mybatis核心配置文件中注册!-->
    <mappers>
        <mapper resource="com/carry/dao/UserMapper.xml"/>
    </mappers>
  1. 测试
@Test
public void test(){
  //第一步:获得SqlSession对象
  SqlSession sqlSession = MybatisUtils.getSqlSession();
  UserDao userDao = sqlSession.getMapper(UserDao.class);
  List<User> userList = userDao.getUserList();
  for (User user : userList) {
    System.out.println(user);
 }
  //关闭SqlSession
  sqlSession.close();
}

二、配置解析

1.MyBatis的核心配置文件

mybatis-config.xml是MyBatis的核心配置文件,其中包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:

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

2.属性配置

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

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

(2)引入外部配置文件并在 properties 元素的子元素中添加设置

	<!--引入外部配置文件-->
	<properties resource="db.properties">
		<property name="username" value="root"/>
		<property name="pwd" value="11111"/>
	</properties>

如果一个属性在不只一个地方进行了配置,那么,MyBatis 将按照下面的顺序来加载:

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

3.设置

这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。下表列举了设置中部分设置的含义、默认值等。

设置名描述有效值默认值
cacheEnabled全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。true falsetrue
logImpl指定 MyBatis 所用日志的具体实现,未指定时将自动查找。SLF4J、LOG4J、LOG4J2、JDK_LOGGING、COMMONS_LOGGING、STDOUT_LOGGING、NO_LOGGING未设置

4.类型别名

类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。例如:

<!--可以给实体类起别名-->
<typeAliases>
	<typeAlias type="org.example.pojo.User" alias="User"/>
</typeAliases>

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

<!--可以给实体类起别名-->
<typeAliases>
	<package name="org.example.pojo"/>
</typeAliases>

扫描实体类的包,它的默认别名就为这个类的类名,首字母小写。 比如 org.example.pojo.User的别名为 user。如果需要更改别名,可以在实体类上增加注解Alias。

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

5.环境配置

MyBatis 可以配置成适应多种环境,这种机制有助于将 SQL 映射应用于多种数据库之中, 现实情况下有多种理由需要这么做。例如,开发、测试和生产环境需要有不同的配置;或者想在具有相同 Schema 的多个生产数据库中使用相同的 SQL 映射。还有许多类似的使用场景。
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

transactionManager(事务管理器)
在 MyBatis 中有两种类型的事务管理器:

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

dataSource(数据源)

dataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源,有三种内建的数据源类型:

  • UNPOOLED:这个数据源的实现会每次请求时打开和关闭连接。虽然有点慢,但对那些数据库连接可用性要求不高的简单应用程序来说,是一个很好的选择。
  • POOLED:这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来,避免了创建新的连接实例时所必需的初始化和认证时间。 这种处理方式很流行,能使并发 Web 应用快速响应请求。
  • JNDI:这个数据源实现是为了能在如 EJB 或应用服务器这类容器中使用,容器可以集中或在外部配置数据源,然后放置一个 JNDI 上下文的数据源引用。

6.映射器

在定义 SQL 映射语句了之前,我们需要告诉 MyBatis 到哪里去找到这些语句。 在自动查找资源方面,Java 并没有提供一个很好的解决方案,所以最好的办法是直接告诉 MyBatis 到哪里去找映射文件。 我们可以使用相对于类路径的资源引用,或类名和包名等。例如:
方式一:使用相对于类路径的资源引用

<!--使用相对于类路径的资源引用-->
<mappers>
	<mapper resource="org/example/dao/UserMapper.xml"/>
</mappers>

方式二:使用映射器接口实现类的完全限定类名

<!--使用映射器接口实现类的完全限定类名-->
<mappers>
	<mapper class="org.example.dao.UserMapper"/>
</mappers>

方式三:将包内的映射器接口实现全部注册为映射器

<!--将包内的映射器接口实现全部注册为映射器-->
<mappers>
	<package name="org.example.dao"/>
</mappers>

三、增删改查

1.select

在MyBatis中执行一个select语句步骤如下:
(1)新建一个Mapper接口

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

(2)在mapper.xml中进行相应的配置

<select id="getUserById" parameterType="int" resultType="org.example.pojo.User">
    select * from mybatis.user where id = #{id}
</select>
  • id : 就是对应的namespace中的方法名;
  • resultType:Sql语句执行的返回值!
  • parameterType :参数类型

(3)测试

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

2.insert

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

3.update

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

4.delete

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

5.万能的Map

如果我们的数据库表中的字段、实体类或者参数过多的时候,可以使用万能的Map用来存储属性。
实例如下:

  //万能的Map
  int addUser2(Map<String,Object> map);
<!--对象中的属性,可以直接取出来  传递map的key-->
<insert id="addUser" parameterType="map">
	insert into mybatis.user (id, pwd) values (#{userid},#{passWord});
</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",5);
	map.put("passWord","2222333");
	mapper.addUser2(map);
	sqlSession.close();
}

6.字段名与属性名不一致的问题

在实际使用过程中,经常会出现数据库中的字段名与实体类中的属性名不一致,这种情况就会导致无法从数据库中取出值。为此,我们可以采用别名或ResultMap(结果集映射)的方式,来解决该问题。
(1)数据库表如下:

idnamepwd
1张三123456
2李四123321

(2)实体类如下:

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

可见实体类password属性名与数据库pwd字段名不一致
解决办法一:起别名

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

解决办法二:结果集映射

<!--结果集映射-->
<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>

7.分页查询

(1)Limit分页

使用SQL实现分页,SQL中limit的语法

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

使用Limit分页示例如下:
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();
	UserMapper mapper = sqlSession.getMapper(UserMapper.class);
	HashMap<String, Integer> map = new HashMap<String, Integer>();
  	map.put("startIndex",1);
 	map.put("pageSize",2);
  	List<User> userList =  mapper.getUserByLimit(map);
	for (User user : userList) {
		System.out.println(user);
	}
	sqlSession.close();
}
(2)RowBounds分页

不再使用SQL实现分页
使用RowBounds分页示例如下:
1.接口

//分页
List<User> getUserByRowBounds();

2.mapper.xml文件

<!--分页-->
<select id="getUserByRowBounds" resultMap="UserMap">
	select * from mybatis.user
</select>

3.测试

@Test
public void getUserByRowBounds(){
	SqlSession sqlSession = MybatisUtils.getSqlSession();
	//RowBounds实现
	RowBounds rowBounds = new RowBounds(1, 2);
	//通过Java代码层面实现分页
	List<User> userList = sqlSession.selectList("org.example.dao.UserMapper.getUserByRowBounds",null,rowBounds);
	for (User user : userList) {
		System.out.println(user);
	}
	sqlSession.close();
}	
(3)插件分页

在这里插入图片描述
了解即可

四、日志

1.简述

Mybatis 通过使用内置的日志工厂提供日志功能。内置日志工厂将会把日志工作委托给下面的实现之一:

  • SLF4J
  • Apache Commons Logging
  • Log4j 2
  • Log4j
  • JDK logging

MyBatis 内置日志工厂会基于运行时检测信息选择日志委托实现。它会(按上面罗列的顺序)使用第一个查找到的实现。当没有找到这些实现时,将会禁用日志功能。

2.STDOUT_LOGGING标准日志输出

在mybatis核心配置文件中,配置我们的日志

<settings>
	<!--标准的日志工厂实现-->
	<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

STDOUT_LOGGING在控制台输出结果:在这里插入图片描述

3.Log4j

1.导入Log4j依赖

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

2.配置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/example.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>
	<!--LOG4J日志工厂实现-->
    <setting name="logImpl" value="LOG4J"/>
</settings>

4.测试结果
在这里插入图片描述

五、注解的使用

1.面向接口编程

(1)使用面向接口开发的根本原因 : 解耦 , 可拓展 , 提高复用 , 分层开发中 , 上层不用管具体的实现 , 大家都遵守共同的标准 , 使得开发变得容易 , 规范性更好。

(2)关于接口的理解

  • 接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。
  • 接口的本身反映了系统设计人员对系统的抽象理解。
  • 接口应有两类:
    • 第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class);
    • 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface);
  • 一个体有可能有多个抽象面。抽象体与抽象面是有区别的。

(3)三个面向区别

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

2.使用注解增删改查

public interface UserMapper {
	@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);
}

3.Lombok

使用步骤:

  1. 在IDEA中安装Lombok插件!
  2. 在项目中导入lombok的jar包
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<version>1.18.10</version>
</dependency>
  1. 在实体类上加注解即可!
@Data
@AllArgsConstructor
@NoArgsConstructor
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger
@Data
@Builder
@Singular
@Delegate
@Value
@Accessors
@Wither
@SneakyThrows

六、一对多与多对一

1.什么是多对一与一对多

在这里插入图片描述

  • 多个学生,对应一个老师
  • 对于学生这边而言, 关联:多个学生,关联一个老师 【多对一】
  • 对于老师而言, 集合: 一个老师,有很多学生 【一对多】
    在这里插入图片描述
    创建如下数据库表来模拟一对多与多对一的情况。
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');

2.多对一

(1)按照查询嵌套处理
    <!--按照查询嵌套处理-->
    <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>
(2)按照结果嵌套处理
    <!--按照结果嵌套查询-->
    <select id="getStudent2" resultMap="StudentTeacher2">
        select s.id sid,s.name sname,t.name tname
        from student as s , teacher as 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"/>
        </association>
    </resultMap>

3.多对一

(1)按照查询嵌套处理
    <!--按照查询嵌套处理-->
    <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>
(2)按照结果嵌套处理
    <!--按结果嵌套查询-->
    <select id="getTeacher" resultMap="TeacherStudent">
        select s.id sid,s.name sname,t.name tname,t.id tid
        from student as s , teacher as 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>

4.小结

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

七、动态sql

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

1.if

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

2.choose

    <select id="queryBlogChoose" parameterType="map" resultType="blog">
        select * from mybatis.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>

3.trim (where,set)

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

4.SQL片段

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

5.Foreach

    <!--
        select * from mybatis.blog where 1=1 and (id=1 or id=2 or id=3)
        我们现在传递一个万能的map,这map中可以存在一个集合!
    -->
    <select id="queryBlogForeach" parameterType="map" resultType="blog">
        select * from mybatis.blog
        <where>
            <foreach collection="ids" item="id" open="and (" close=")" separator="or">
                id = #{id}
            </foreach>
        </where>
    </select>

八、缓存

1.简介

  1. 什么是缓存
    存在内存中的临时数据。将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
  2. 为什么使用缓存?
    减少和数据库的交互次数,减少系统开销,提高系统效率
  3. MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
    (1)默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)。
    (2)二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
    (3)为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存

2.一级缓存

一级缓存也叫本地缓存: SqlSession。与数据库同一次会话期间查询到的数据会放在本地缓存中。以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库。
测试步骤:

  1. 开启日志!
  2. 测试在一个Sesion中查询两次相同记录
  3. 查看日志输出

3.二级缓存

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

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

步骤:

  1. 开启全局缓存
    <settings>
        <!--显示的开启全局缓存-->
        <setting name="cacheEnabled" value="true"/>
    </settings>
  1. 在要使用二级缓存的Mapper中开启,也可以自定义参数
    <!--在当前Mapper.xml中使用二级缓存-->
    <cache/>
  1. 测试

4.自定义缓存(ehcache)

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

(1)要在程序中使用ehcache,先要导包!

	<!-- 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>

(2)在mapper中指定使用我们的ehcache缓存实现!

    <!--在当前Mapper.xml中使用二级缓存-->
    <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

(3)配置ehcache.xml

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

helloWorldZMY

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值