MyBatis

  • 1.简介
  • 1.1 为什么学习MyBatis
  • 1.2 MyBatis的优缺点
  • 1.3 MyBatis和Hibernate的区别
  • 2. 入门
  • 2.1 使用Maven创建
  • 2.2 Spring Boot整合MyBatis (推荐)
  • 3. XML 映射器
  • 3.1 select
  • 3.2 insert
  • 3.3 update
  • 3.4delete
  • 3.5 Map的使用
  • 3.6 模糊查询
  • 3.7 ResultMap(解决属性名和字段名不一致问题)
  • 4. @Param注解作用
  • 4.1 作用
  • 4.2 示例
  • 5.XML配置文件
  • 4.1 属性(properties)
  • 4.2 设置(settings)
  • 4.3 类型别名(typeAliases)
  • 4.4 环境配置(environments)
  • 4.5 映射器(mappers)
  • 5. 作用域(Scope)和生命周期
  • 5.1 SqlSessionFactoryBuilder
  • 5.2 SqlSessionFactory
  • 5.3 SqlSession
  • 6. 日志
  • 6.1 STDOUT_LOGGING(标准日志输出)
  • 6.2 Log4j
  • 日志对象的使用
  • 7. 分页
  • 使用分页插件
  • 8 使用注解开发
  • 9 高级结果映射
  • 9.1 多对一处理
  • 9.2 一对多处理
  • 10 动态SQL
  • **if**
  • **where**
  • **choose (when, otherwise)**
  • **set**
  • **trim (where, set)**
  • **foreach**
  • **trim (where, set)**
  • **SQL片段**


1.简介

  • MyBatis 是一款优秀的持久层框架
  • MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的过程
  • MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 实体类 【Plain Old Java Objects,普通的 Java对象】映射成数据库中的记录。
  • MyBatis 本是apache的一个开源项目ibatis, 2010年这个项目由apache 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github .
  • Mybatis官方文档 : http://www.mybatis.org/mybatis-3/zh/index.html
  • GitHub : https://github.com/mybatis/mybatis-3

1.1 为什么学习MyBatis

  • 传统的JDBC编程步骤
    1、加载数据库驱动
    2、创建并获取数据库链接
    3、创建jdbc statement对象
    4、设置sql语句
    5、设置sql语句中的参数(使用preparedStatement)
    6、通过statement执行sql并获取结果
    7、对sql执行结果进行解析处理
    8、释放资源(resultSet、preparedstatement、connection)
public static void main(String[] args) {
	Connection connection = null;
	PreparedStatement preparedStatement = null;
	ResultSet resultSet = null;

	try {
		// 加载数据库驱动
		Class.forName("com.mysql.jdbc.Driver");

		// 通过驱动管理类获取数据库链接
		connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "root");
		// 定义sql语句 ?表示占位符
		String sql = "select * from user where username = ?";
		// 获取预处理statement
		preparedStatement = connection.prepareStatement(sql);
		// 设置参数,第一个参数为sql语句中参数的序号(从1开始),第二个参数为设置的参数值
		preparedStatement.setString(1, "王五");
		// 向数据库发出sql执行查询,查询出结果集
		resultSet = preparedStatement.executeQuery();
		// 遍历查询结果集
		while (resultSet.next()) {
			System.out.println(resultSet.getString("id") + "  " + resultSet.getString("username"));
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		// 释放资源
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (preparedStatement != null) {
			try {
				preparedStatement.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
  • MyBatis解决的问题
    1、数据库连接创建、释放频繁造成系统资源浪费从而影响系统性能,如果使用数据库连接池可解决此问题。
    解决: 在SqlMapConfig.xml中配置数据连接池,使用连接池管理数据库链接。
    2、Sql语句写在代码中造成代码不易维护,实际应用sql变化的可能较大,sql变动需要改变java代码。
    解决: 将Sql语句配置在XXXXmapper.xml文件中与java代码分离。
    3、向sql语句传参数麻烦,因为sql语句的where条件不一定,可能多也可能少,占位符需要和参数一一对应。
    解决: Mybatis自动将java对象映射至sql语句,通过statement中的parameterType定义输入参数的类型。
    4、对结果集解析麻烦,sql变化导致解析代码变化,且解析前需要遍历,如果能将数据库记录封装成pojo对象解析比较方便。
    解决: Mybatis自动将sql执行结果映射至java对象,通过statement中的resultType定义输出结果的类型。

1.2 MyBatis的优缺点

  • 优点
  1. 基于SQL语句编程,相当灵活,不会对应用程序或者数据库的现有设计造成任
    何影响,SQL写在XML里,解除sql与程序代码的耦合,便于统一管理;提供XML
    标签,支持编写动态SQL语句,并可重用。
  2. 与JDBC相比,减少了50%以上的代码量,消除了JDBC大量冗余的代码,不需
    要手动开关连接;
  3. 很好的与各种数据库兼容(因为MyBatis使用JDBC来连接数据库,所以只要
    JDBC支持的数据库MyBatis都支持)。
  4. 能够与Spring很好的集成;
  5. 提供映射标签,支持对象与数据库的ORM字段关系映射;提供对象关系映射标
    签,支持对象关系组件维护。
  6. 使用的人多(SSM)
  • 缺点
  1. SQL语句的编写工作量较大,尤其当字段多、关联表多时,对开发人员编写
    SQL语句的功底有一定要求。
  2. SQL语句依赖于数据库,导致数据库移植性差,不能随意更换数据库。

1.3 MyBatis和Hibernate的区别

  • 1 相同点
    Hibernate与MyBatis都可以是通过SessionFactoryBuider由XML配置文件生成SessionFactory,然后由SessionFactory 生成Session,最后由Session来开启执行事务和SQL语句。
    其中SessionFactoryBuider,SessionFactory,Session的生命周期都是差不多的。Hibernate和MyBatis都支持JDBC和JTA事务处理。
  • 2 不同点
    (1)hibernate是全自动,而mybatis是半自动
    hibernate完全可以通过对象关系模型实现对数据库的操作,拥有完整的JavaBean对象与数据库的映射结构来自动生成sql。而mybatis仅有基本的字段映射,对象数据以及对象实际关系仍然需要通过手写sql来实现和管理。
    (2)hibernate数据库移植性远大于mybatis
    hibernate通过它强大的映射结构和hql语言,大大降低了对象与数据库(Oracle、MySQL等)的耦合性,而mybatis由于需要手写sql,因此与数据库的耦合性直接取决于程序员写sql的方法,如果sql不具通用性而用了很多某数据库特性的sql语句的话,移植性也会随之降低很多,成本很高。
    (3)hibernate拥有完整的日志系统,mybatis则欠缺一些
    hibernate日志系统非常健全,涉及广泛,包括:sql记录、关系异常、优化警告、缓存提示、脏数据警告等;而mybatis则除了基本记录功能外,功能薄弱很多。
    (4)mybatis相比hibernate需要关心很多细节
    hibernate配置要比mybatis复杂的多,学习成本也比mybatis高。但也正因为mybatis使用简单,才导致它要比hibernate关心很多技术细节。mybatis由于不用考虑很多细节,开发模式上与传统jdbc区别很小,因此很容易上手并开发项目,但忽略细节会导致项目前期bug较多,因而开发出相对稳定的软件很慢,而开发出软件却很快。hibernate则正好与之相反。但是如果使用hibernate很熟练的话,实际上开发效率丝毫不差于甚至超越mybatis。
    (5)sql直接优化上,mybatis要比hibernate方便很多
    由于mybatis的sql都是写在xml里,因此优化sql比hibernate方便很多。而hibernate的sql很多都是自动生成的,无法直接维护sql;虽有hql,但功能还是不及sql强大,见到报表等变态需求时,hql也歇菜,也就是说hql是有局限的;hibernate虽然也支持原生sql,但开发模式上却与orm不同,需要转换思维,因此使用上不是非常方便。总之写sql的灵活度上hibernate不及mybatis。
    (6)缓存机制上,hibernate要比mybatis更好一些
    MyBatis的二级缓存配置都是在每个具体的表-对象映射中进行详细配置,这样针对不同的表可以自定义不同的缓存机制。并且Mybatis可以在命名空间中共享相同的缓存配置和实例,通过Cache-ref来实现。
    而Hibernate对查询对象有着良好的管理机制,用户无需关心SQL。所以在使用二级缓存时如果出现脏数据,系统会报出错误并提示。
  • 3 总结
    MyBatis:机械工具,使用方便,拿来就用,但工作还是要自己来作,不过工具是活的,怎么使由我决定。(小巧、方便、高效、简单、直接、半自动
    Hibernate:智能机器人,但研发它(学习、熟练度)的成本很高,工作都可以摆脱他了,但仅限于它能做的事。(强大、方便、高效、复杂、绕弯子、全自动

2. 入门

2.1 使用Maven创建

  • 项目工程如下
  • mybatis使用function mybatis的用法_hibernate

  • 建立数据库
CREATE DATABASE `jpa`;
USE `jpa`;
CREATE TABLE `user`(
    `id` INT(20) NOT NULL PRIMARY KEY,
    `age` INT(30) DEFAULT NULL,
    `name` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user`(`id`,`age`,`name`) VALUES
(1,10,'小明'),
(2,34,'小李'),
(3,21,'小王');
  • 建pom
<?xml version="1.0" encoding="UTF-8"?>
  <project xmlns="http://maven.apache.org/POM/4.0.0"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <parent>
          <artifactId>Mybatis</artifactId>
          <groupId>com.ui</groupId>
          <version>1.0-SNAPSHOT</version>
      </parent>
      <modelVersion>4.0.0</modelVersion>
  
      <artifactId>Demo</artifactId>
      <dependencies>
          <!--mysql驱动-->
          <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
          <dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
              <version>5.1.46</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-->
          <!-- https://mvnrepository.com/artifact/junit/junit -->
          <dependency>
              <groupId>junit</groupId>
              <artifactId>junit</artifactId>
              <version>4.12</version>
              <scope>test</scope>
          </dependency>
  
      </dependencies>
      <properties>
          <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
  
      <build>
          <resources>
              <resource>
                  <directory>src/main/resources</directory>
                  <includes>
                      <include>**/*.properties</include>
                      <include>**/*.xml</include>
                  </includes>
                  <filtering>true</filtering>
              </resource>
              <resource>
                  <directory>src/main/java</directory>
                  <includes>
                      <include>**/*.properties</include>
                      <include>**/*.xml</include>
                  </includes>
                  <filtering>true</filtering>
              </resource>
          </resources>
      </build>
  </project>
  • 写配置文件
    文件名: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.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/jpa?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--每一个Mapper.XML都需要在Mybatis核心配置文件中注册-->
    <mappers>
        <mapper resource="com/ui/dao/UserMapper.xml"/>
    </mappers>

</configuration>
  • 编写业务类
public class User {
    private Integer id;
    private String name;
    private Integer age;

    public User(String name, Integer age){
        this.name = name;
        this.age = age;
    }
  • 编写DAO接口
public interface UserDao {
    List<User> getUserList(); //实现查询数据库
}
  • 编写Mapper文件
    通常在此处进行编写sql语句。
<?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.ui.dao.UserDao">
    <!--    sql查询语句-->
    <select id="getUserList" resultType="com.ui.pojo.User">
        select * from jpa.user
    </select>
</mapper>
  • 编写Mapper文件
  • 编写连接工具类
//sqlSessionFactory
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();
    }
}
  • 测试
public class UserDaoTest {
    @Test
    public void test(){
        //第一步:获取sqlsession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        //1.getmapper(推荐)
        //该方法有很多优势,首先它不依赖于字符串字面值,会更安全一点;其次,如果你的 IDE 有代码补全功能,那么代码补全可以帮你快速选择到映射好的 SQL 语句
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        //List<User> userList = mapper.getUserList();
        //2.直接使用
        //List<User> userList = sqlSession.selectList("com.ui.dao.UserDao.getUserList");

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

    }
}
  • 测试结果

mybatis使用function mybatis的用法_sql_02

2.2 Spring Boot整合MyBatis (推荐)

  • 项目工程如下
  • mybatis使用function mybatis的用法_mybatis_03

  • 建立数据库
CREATE DATABASE `jpa`;
USE `jpa`;
CREATE TABLE `user`(
    `id` INT(20) NOT NULL PRIMARY KEY,
    `age` INT(30) DEFAULT NULL,
    `name` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user`(`id`,`age`,`name`) VALUES
(1,10,'小明'),
(2,34,'小李'),
(3,21,'小王');
  • 建pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.yinan</groupId>
    <artifactId>SpringBootMyBatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <dependencies>


        <!-- Spring Boot Mybatis 依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!--mysql-connector-java-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <!-- Spring Boot Web 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Spring Boot Test 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

    </dependencies>
</project>
  • 写Application.properties
## Mybatis 配置
##mybatis.typeAliasesPackage指向实体类包路径。
mybatis.typeAliasesPackage=com.yinan.springboot.entities
# mybatis.mapperLocations 配置为 classpath 路径下 mapper 包下, * 代表会扫描所有 xml ?件。
mybatis.mapperLocations=classpath:mapper/*.xml


spring.datasource.name=jpa
spring.datasource.url=jdbc:mysql://localhost:3306/jpa?useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=12345
  • 启动类
@SpringBootApplication
// ⽤这个注解可以注册 Mybatis mapper 接⼝类。
@MapperScan("com.yinan.springboot.dao")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}
  • 业务类
public class User {
    private Integer id;
    private String name;
    private Integer age;

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public User() {
    }

    public User(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
    //getset方法
  • dao层
@Component
public interface UserDao {
    User findById(@Param("id") Integer name);
}
  • 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.yinan.springboot.dao.UserDao">
    <!--    sql查询语句-->
    <select id="findById" parameterType="java.lang.Integer" resultType="com.yinan.springboot.entities.User">
        select  *
        from user
        where id = #{id,jdbcType=INTEGER}
    </select>
</mapper>
  • Service层
public interface UserService {
    //通过用户id获取对象
    User getUserById(Integer id);
}
  • Service层实现类
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Override
    public User getUserById(Integer id) {
        User user = userDao.findById(id);
        return user;
    }
}
  • Controller层
@RestController
@RequestMapping(value = "/users")
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping(value = "/{id}")
    public User getUser(@PathVariable(name = "id") Integer id){
        //路径:http://localhost:8080/users/1
        return userService.getUserById(id);
    }
//    @GetMapping
//    public User getUser(@RequestParam(name = "id") Integer id){
          //http://localhost:8080/users?id=1
//        return userService.getUserById(id);
//    }
}
  • 启动主启动类进行web测试

3. XML 映射器

MyBatis 的真正强大在于它的语句映射,这是它的魔力所在,MyBatis 致力于减少使用成本,让用户能更专注于 SQL 代码。
SQL 映射文件只有很少的几个顶级元素(按照应被定义的顺序列出):

  • cache – 该命名空间的缓存配置。
  • cache-ref – 引用其它命名空间的缓存配置。
  • resultMap – 描述如何从数据库结果集中加载对象,是最复杂也是最强大的元素。
  • sql – 可被其它语句引用的可重用语句块。
  • insert – 映射插入语句。
  • update – 映射更新语句。
  • delete – 映射删除语句。
  • select – 映射查询语句。

3.1 select

  • 选择、查询语句:
  • id:就是对应的namespace中的方法名
  • resultType: sql语句执行的返回值!
  • parameterType:参数类型
  • 1.编写接口
//根据id查询用户
User getUserById(int id);
  • 2.编写mapper中对应的sql语句
    注意参数符号: #{id} :占位符
<select id="getUserById" parameterType="int" resultType="com.ui.pojo.User">
   select * from user where id = #{id};
</select>
  • 3.编写测试
@Test
public void testGetUserById(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    User user = mapper.getUserById(1);
    System.out.println(user);
    sqlSession.close();
}

3.2 insert

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

//insert一个用户
int addUser(User user);
<insert id="addUser" parameterType="com.ui.pojo.User">
    insert into user (id,name,age) value(#{id},#{name},#{age});
</insert>
@Test
public void testAddUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    int user = mapper.addUser(new User(4, "哈哈", 12));
    //提交事务
    sqlSession.commit();
    sqlSession.close();
}

3.3 update

//修改用户
int updateUser(User user);
<update id="updateUser" parameterType="com.ui.pojo.User">
    update user set name=#{name},age=#{age} where id = #{id};
</update>
@Test
public void testUpdateUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    mapper.updateUser(new User(4,"呵呵",13));
    sqlSession.commit();
    sqlSession.close();
}

3.4delete

//删除一个用户
int deleteUser(int id);
<delete id="deleteUser" parameterType="int">
    delete from user where id = #{id};
</delete>
@Test
public void testDeleteUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    mapper.deleteUser(4);
    sqlSession.commit();
    sqlSession.close();
}

3.5 Map的使用

假设我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑用map,表的列名和属性名可以不一致。

//万能的map
int addUser2(Map<String,Object> map);
<!--
    对象中的属性,可以直接取出来
    传递map的key
-->
<insert id="addUser2" parameterType="map">
    insert into user (id,name,age) value(#{userid},#{userName},#{userage});
</insert>
@Test
public void testAddUser2(){
    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","Hello");
    map.put("userage",23);
    mapper.addUser2(map);
    sqlSession.close();
}

3.6 模糊查询

用法

public interface UserDao {
    List<User> getUserList();

    List<User> getUserLike(String s);
}
<select id="getUserLike" parameterType="string" resultType="com.ui.pojo.User">
        select * from user where name like #{value}
    </select>
@Test
    public void testAddUser2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> userLike = mapper.getUserLike("%李%");
        for (User user : userLike) {
            System.out.println(user);
        }
        sqlSession.close();
    }

注意上述方法可能会出现sql注入的问题:
把sql语句写死即可:

<select id="getUserLike" resultType="com.ui.pojo.User">
    select * from mybatis.user where name like "%"#{value}"%";
</select>

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

  • resultMap元素是 MyBatis 中最重要最强大的元素。
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
  • ResultMap 的优秀之处——你完全可以不用显式地配置它们。 虽然上面的例子不用显式配置 ResultMap。 但为了讲解,我们来看看如果在刚刚的示例中,显式使用外部的 resultMap 会怎样,这也是解决列名不匹配的另外一种方式。
  • resultType 和 resultMap 之间只能同时使用一个。
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ui.dao.UserMapper">
<!--    结果集映射-->
    <resultMap id="UserMap" type="User">
<!-- column数据库中的字段,property实体类中的属性       -->
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="age" property="userAge"/>
    </resultMap>
    <select id="getUserById" parameterType="int" resultMap="UserMap">
       select * from user where id = #{id};
    </select>
</mapper>

4. @Param注解作用

4.1 作用

@Param是MyBatis所提供的(org.apache.ibatis.annotations.Param),作为Dao层的注解,作用是用于传递多个参数,从而可以与SQL中的的字段名相对应,一般在2~5时使用最佳。

4.2 示例

public List<User> findUser(@Param("userName") String userName, @Param("userAge") String userAge);

5.XML配置文件

MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:

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

4.1 属性(properties)

我们可以通过properties属性来实现引用配置文件,这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。
例如:
1. 编写一个配置文件:db.properties

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

在核心配置文件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="test">
        <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>

        <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/jpa?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="110120"/>
            </dataSource>
        </environment>
    </environments>
    <!--每一个Mapper.XML都需要在Mybatis核心配置文件中注册-->
    <mappers>
        <mapper resource="com/ui/dao/UserMapper.xml"/>
    </mappers>
</configuration>

2.不引入外部文件,直接在properties标签里写

<properties >
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/jpa?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="12345"/>
    </properties>

4.2 设置(settings)

这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。 下表描述了设置中各项设置的含义、默认值等。(详细说明参考官方文档)

设置名

描述

有效值

默认值

cacheEnabled

全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。

true or false

true

logImpl

指定 MyBatis 所用日志的具体实现,未指定时将自动查找。

SLF4J or LOG4J or LOG4J2 or JDK_LOGGING or COMMONS_LOGGING or STDOUT_LOGGING or NO_LOGGING

未设置

4.3 类型别名(typeAliases)

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

<typeAliases>
        <typeAlias type="com.ui.pojo.User" alias="User"/>
    </typeAliases>

对应的mapper

<select id="getUserList" resultType="User">
        select * from user
    </select>

第二种:
指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,扫描实体类的包,它的默认别名为这个类的类名,首字母小写(不区分大小写,建议小写)!

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

第三种:
注解,别名为其注解值。
在User类中加入注解:

@Alias("user")
public class User {
......
}

对应的mapper

<select id="getUserList" resultType="user">
        select * from user
    </select>

下面是一些为常见的 Java 类型内建的类型别名。它们都是不区分大小写的,注意,为了应对原始类型的命名重复,采取了特殊的命名风格。(详细说明参考官方文档)

mybatis使用function mybatis的用法_mybatis_04

4.4 环境配置(environments)

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

<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>
</environments>

注意一些关键点:

  • 默认使用的环境 ID(比如:default=“development”)。
  • 每个 environment 元素定义的环境 ID(比如:id=“development”)。
  • 事务管理器的配置(比如:type=“JDBC”)。
  • 数据源的配置(比如:type=“POOLED”)。

4.5 映射器(mappers)

既然 MyBatis 的行为已经由上述元素配置完了,我们现在就要来定义 SQL 映射语句了。 但首先,我们需要告诉 MyBatis 到哪里去找到这些语句。 在自动查找资源方面,Java 并没有提供一个很好的解决方案,所以最好的办法是直接告诉 MyBatis 到哪里去找映射文件。 你可以使用相对于类路径的资源引用,或完全限定资源定位符(包括 file:/// 形式的 URL),或类名和包名等。例如:

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

5. 作用域(Scope)和生命周期

理解我们之前讨论过的不同作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。

mybatis使用function mybatis的用法_hibernate_05

5.1 SqlSessionFactoryBuilder

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

5.2 SqlSessionFactory

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

5.3 SqlSession

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

6. 日志

在xml配置文件中配置。

设置名

描述

有效值

默认值

logImpl

指定 MyBatis 所用日志的具体实现,未指定时将自动查找。

SLF4J or LOG4J or LOG4J2 or JDK_LOGGING or COMMONS_LOGGING or STDOUT_LOGGING or NO_LOGGING

未设置

6.1 STDOUT_LOGGING(标准日志输出)

在mybatic核心配置文件:mybatis-config.xml中,配置我们的日志:

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

6.2 Log4j

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

使用:

  1. 先导入log4j的包
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
  1. 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/Mybatis.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. 配置log4j为日志的实现
<settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
  1. log4j的使用
    直接运行测试类。

日志对象的使用

//日志对象,加载参数为当前类的class。
static Logger logger = Logger.getLogger(UserMapperTest.class);
  • 使用不同的日志级别。
    logger.info(“info:进入了testLog4j”);
    logger.debug(“debug:进入了testLog4j”);
    logger.error(“error:进入了testLog4j”);

7. 分页

1.接口

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

2.Mapper.xml

<!--    分页-->
    <select id="getUserByLimit" parameterType="map" resultType="User">
        select * from user limit #{startIndex},#{pageSize};
    </select>

3.测试

mybatis使用function mybatis的用法_sql_06

使用分页插件

https://pagehelper.github.io/

PageHelper

8 使用注解开发

了解即可。

  • 1.注解在接口上实现
@Select("select * from user")
List<User> getUsers();
  • 2.需要在核心配置文件中绑定接口
<mappers>
    <mapper class="com.kuang.dao.UserMapper"/>
</mappers>
  • 3.测试使用
@Test
public void test(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    //底层主要应用反射
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> users = mapper.getUsers();
    for (User user : users) {
        System.out.println(user);
    }

    sqlSession.close();
}

9 高级结果映射

9.1 多对一处理

示例:

  • 多个学生对应一个老师
    对于学生这边而言,关联,多个学生关联一个老师【多对一】
    对于老师而言,集合,一个老师有很多学生【一对多】
  • SQL:
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.新建实体类

@Data
public class Student {
    private int id;
    private String name;
    //学生需要关联一个老师
    private Teacher teacher;
}
@Data
public class Teacher {
    private int id;
    private String name;
}

2.建立Mapper接口

  • StudentMapper
public interface StudentMapper {
    //查询所有的学生信息,以及对应的老师的信息
    public List<Student> getStudent();
}
  • StudentMapper.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 namespace="com.ui.dao.StudentMapper">
    <!--思路
        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>


</mapper>
  • TeacherMapper
public interface TeacherMapper {
    Teacher getTeacher();
}
  • TeacherMapper.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 namespace="com.ui.dao.TeacherMapper">
    <!--    sql查询语句-->
    <select id="getTeacher" resultType="Teacher">
        select * from teacher
    </select>


</mapper>
  1. 注册我们的Mapper接口
<mappers>
    <mapper resource="com/ui/dao/UserMapper.xml"/>
    <mapper resource="com/ui/dao/CountryMapper.xml"/>
    <mapper resource="com/ui/dao/StudentMapper.xml"/>
    <mapper resource="com/ui/dao/TeacherMapper.xml"/>
</mappers>
  1. 测试
@Test
public void testStudent(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    List<Student> studentList = mapper.getStudent();
    for (Student student : studentList) {
        System.out.println(student);
    }
    sqlSession.close();
}

9.2 一对多处理

示例:
一个老师拥有多个学生,对于老师而言就是一对多的关系。
1.新建实体类

@Data
public class Student {
    private int id;
    private String name;
    private int tid;
}
@Data
public class Teacher {
    private int id;
    private String name;
    //一个老师拥有多个学生
    private List<Student> students;
}

2.建立Mapper接口

  • StudentMapper
public interface StudentMapper {
    //查询所有的学生信息,以及对应的老师的信息
    public List<Student> getStudent();
}
  • StudentMapper.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 namespace="com.ui.dao.StudentMapper">
    <!--思路
        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>


</mapper>
  • TeacherMapper
public interface TeacherMapper {
    //获取指定老师下的所有学生及老师的信息
    Teacher getTeacher(@Param("tid") int id);
}
  • TeacherMapper.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 namespace="com.ui.dao.TeacherMapper">
    <!--    sql查询语句-->
    <select id="getTeacher" resultMap="TeacherStudent2">
        select * from teacher where id = #{tid}
    </select>
    <resultMap id="TeacherStudent2" type="Teacher">
        <collection property="students" column="id" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId"></collection>
    </resultMap>

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

</mapper>
  1. 注册我们的Mapper接口
<mappers>
    <mapper resource="com/ui/dao/UserMapper.xml"/>
    <mapper resource="com/ui/dao/CountryMapper.xml"/>
    <mapper resource="com/ui/dao/StudentMapper.xml"/>
    <mapper resource="com/ui/dao/TeacherMapper.xml"/>
</mappers>
  1. 测试
@Test
public void testStudent(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher(1);
        System.out.println(teacher);
        sqlSession.close();
}

10 动态SQL

动态SQL:根据不同的条件生成不同的SQL语句.本质还是SQL语句,只是我们可以在SQL层面去执行一些逻辑代码

if

如果希望由不同的查询出不同的结果,使用if标签进行条件判断。
案例:

mapper

public interface BlogMapper {
    //查询博客
    List<Blog> queryBlogIF(Map map);
}

xml

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

test

@Test
    public void test5(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        //objectObjectHashMap.put("title","das");
        objectObjectHashMap.put("author","ter");
        List<Blog> blogs = mapper.queryBlogIF(objectObjectHashMap);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

where

where标签自动去除and
案例:

mapper

public interface BlogMapper {
    //查询博客
    List<Blog> queryBlogChoose(Map map);
}

xml

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

test

@Test
    public void test6(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("title","das");
        objectObjectHashMap.put("author","ter");
  
        List<Blog> blogs = mapper.queryBlogChoose(objectObjectHashMap);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

choose (when, otherwise)

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
注意:只会选择一个条件进行查询,若都不满足,则进入otherwise标签进行查询。
案例:

mapper

public interface BlogMapper {
    //查询博客
    List<Blog> queryBlogChoose(Map map);
}

xml

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

test

@Test
    public void test6(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        //objectObjectHashMap.put("title","das");
        //objectObjectHashMap.put("author","ter");
        objectObjectHashMap.put("views","2323");
        List<Blog> blogs = mapper.queryBlogChoose(objectObjectHashMap);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

set

用于动态更新语句的类似解决方案叫做 set。set 元素可以用于动态包含需要更新的列,忽略其它不更新的列。set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)
案例:

mapper

public interface BlogMapper {
    //更新博客
    int updateBlog(Map map);
}

xml

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

案例

@Test
    public void test7(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("title","das");
        //objectObjectHashMap.put("author","ter");
        objectObjectHashMap.put("id","1");
        mapper.updateBlog(objectObjectHashMap);

        sqlSession.close();
    }

trim (where, set)

是一种动态sql标签。
如去指定的后缀相当于where标签。
<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>

foreach

foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。
案例:

mapper

public interface BlogMapper {
    //查询第1-2-3号记录的博客
    List<Blog> queryBlogForEach(Map map);
}

xml

<!--select * from blog where (id = 1 or id = 2 or id = 3)-->
    <select id="queryBlogForEach" parameterType="map" resultType="com.ui.pojo.Blog">
        select * from blog
        <where>
            <foreach collection="ids" item="id" open="and (" close=")" separator="or">
                id = #{id}
            </foreach>
        </where>
    </select>

test

@Test
    public void test8(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        ArrayList<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(2);
        map.put("ids", ids);
        List<Blog> blogs = mapper.queryBlogForEach(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

trim (where, set)

是一种动态sql标签。
如去指定的后缀相当于where标签。
<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>

SQL片段

有的时候,我们可能将一些公共的功能抽取出来复用。

1.使用sql标签抽取公共部分

<sql id="if_id">
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="author !=null">
            and author = #{author}
        </if>
    </sql>

2.在需要使用的地方,使用include标签引用即可

<select id="queryBlogIF" parameterType="map" resultType="com.ui.pojo.Blog">
        select * from blog where 1=1
        <include refid="if_id"></include>
    </select>

注意事项:

  • 最好基于单表来定义SQL片段,复杂的话,复用就比较差了。
  • SQL片段尽量不要包含where标签。