mybatis

难点:

一对多多对一

动态SQL

1.1 什么是Mybatis

如何获得Mybatis

maven仓库:

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

中文文档:mybatis – MyBatis 3 | 简介

1.2 持久化

数据持久化

  • 持久化就是将程序的数据在持久状态和瞬时状态转化的过程

  • 内存:断电即失

  • 数据库(Jdbc),io文件持久化

  • 生活方面例子:冷藏,罐头。

为什么需要持久化?

  • 不想丢掉一些对象

  • 内存太贵

1.3 持久层

Dao层,Service层,Controller层…

  • 完成持久化工作的代码块

  • 层界限十分明显

1.4 为什么需要Mybatis?

  • 帮助程序猿将数据存入到数据库中

  • 方便

  • 传统的JDBC代码太复杂,简化–>框架–>自动化

2、第一个Mybatis程序

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

2.1 搭建环境

1.搭建数据库

2.新建一个空的maven项目

3.删除src目录

4.导入依赖 mysql驱动

<dependencies><!--mysql驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.46</version></dependency><!--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.11</version><scope>test</scope></dependency>
</dependencies>
​<!--资源过滤--><build><resources><resource><directory>src/main/java</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource><resource><directory>src/main/resources</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource></resources></build>

2.2.创建模块

  • 编写mybatis核心配置文件

命名mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--核心配置文件-->
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/><property name="username" value="root"/><property name="password" value="123456"/></dataSource></environment></environments><!--每一个mapper.xml都需要在Mybatis核心配置文件注册!--><mappers><mapper resource="org/mybatis/example/BlogMapper.xml"/></mappers>
</configuration>
  • 编写mybatis工具类

//SqlSessionFactory 构建  SqlSession
public class MybatisUtils {
​private static SqlSessionFactory sqlSessionFactory;
​
​static {try {//第一步:获取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();}
}

2.3.编写代码

  • 实体类pojo

package com.hui.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;}
​@Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + '\'' +", pwd='" + pwd + '\'' +'}';}
}
  • dao接口

public interface UserDao {List<User> getUserList();
​
}
  • 接口实现类由原来的UserDaoImpl转变为一个mapper配置文件

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--绑定一个指定的dao接口--><mapper namespace="com.hui.dao.UserDao"><!--id对应dao接口中的方法名--><!--resultType里面要写实体类的全限定名--><select id="getUserList" resultType="com.hui.pojo.User">select * from mybatis.user</select>
    </mapper>

2.4测试

public class UserDaoTest {@Testpublic void test() {//第一步 获得sqlSession对象SqlSession sqlSession = MybatisUtils.getSqlSession();//方式1 getMapperUserDao userDao = sqlSession.getMapper(UserDao.class);List<User> userList = userDao.getUserList();for (User user : userList) {System.out.println(user);}//关闭sqlSessionsqlSession.close();}
}

3、CRUD

3.1 namespace

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

3.2 select

选择,查询语句;

  • id:就是对应的namespace中的方法名;

  • resultType:Sql语句执行的返回值!

  • parameterType:参数类型!

1.编写接口

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

2.编写对应的mapper中的sql语句

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

3.测试

    @Testpublic void getUserById(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);User user = mapper.getUserById(1);System.out.println(user);//关闭SqlSessionsqlSession.close();
}

3.3 Insert

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

3.4 Update

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

3.5 Delete

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

注意点:

增删改需要提交事务!

3.6万能的map

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

User addUser2(Map<String,Object> map);
<insert id="addUser" parameterType="map" >insert into mybatis.user (id,name,pwd)values (#{userid},#{userName},#{password});
</insert>
@Test
public void addUser2() {//第一步 获得sqlSession对象SqlSession sqlSession = MybatisUtils.getSqlSession();//方式1 getMapperUserMapper userDao = sqlSession.getMapper(UserMapper.class);Map<String, Object> map = new HashMap<>();map.put("userid",5);map.put("userName","王五");map.put("password","123455");userDao.addUser2(map);//增删改需要提交事物sqlSession.commit();//关闭sqlSessionsqlSession.close();
}

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

3.7模糊查询

java代码执行的时候,传递通配符% %

List<User> userList = mapper.getUserLike("%李%");

在sql拼接中使用通配符!

select * from mybatis.user where name like "%"#{value}"%"

4、配置解析

4.1 核心配置文件

mybatis-config.xml MyBatis的配置文件包含了会深深影响MyBatis行为的设置和属性信息。

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

4.2 环境配置(environments)

数据源:就是连接数据库

默认事物管理器:JDBC

默认连接池:POOLED

4.3 属性(properties)

我们可以通过properties属性来实现引用配置文件 这些属性都是可外部配置且可动态替换的,既可以在典型的Java属性文件中配置,亦可通过properties元素的子元素来传递。 编写一个配置文件 : db.properties

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

在核心配置文件中映入

<!--引入外部配置文件-->
<properties resource="db.properties"/>
  • 可以直接引入外部文件

  • 可以在其中增加一些属性配置

  • 如果两个文件有同一个字段,优先使用外部配置文件的!

4.4 类型别名(typeAliases)

  • 类型别名是为Java类型设置一个短的名字。

  • 存在的意义仅在于用来减少类完全限定名的冗余。

  • 别名只和xml有关 写在xml中

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

也可以指定一个包名,MyBatis会在包名下面搜索需要的JavaBean,比如: 扫描实体类的包,它的默认别名就为这个类的类名,首字母小写!

<!--扫描包-->
<typeAliases><package name="com.kuang.pojo"/>
</typeAliases>
  • 在实体类比较少的时候,使用第一种方式。

  • 如果实体类十分多,建议使用第二种。

  • 第一种可以DIY别名,第二种则不行,如果非要改,需要在实体上增加注解

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

4.5映射器(mappers)

MapperRegistry:注册绑定我们的Mapper文件; 方式一:【推荐使用】

<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册!-->
<mappers><mapper resource="com/kuang/dao/UserMapper.xml"/>
</mappers>

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

<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册!-->
<mappers><mapper class="com.kuang.dao.UserMapper"/>
</mappers>

注意点:

接口和它的Mapper配置文件必须同名! 接口和它的Mapper配置文件必须在同一个包下! 方式三:使用扫描包进行注入绑定

<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册!-->
<mappers><package name="com.kuang.dao"/>
</mappers>

注意点:

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

4.6 生命周期和作用域

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

SqlSessionFactoryBuilder:

  • 一旦创建了 SqlSessionFactory,就不再需要它了。

  • 局部变量

SqlSessionFactory:

  • 说白就是可以想象为:数据库连接池。

  • SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。

  • SqlSessionFactory 的最佳作用域是应用作用域。

  • 最简单的就是使用单例模式或者静态单例模式。

SqlSession:

  • 连接到连接池的一个请求!

  • SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。

  • 用完后需要赶紧关闭,否则资源被占用!

这里的每一个Mapper,就代表一个具体的业务 !

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

  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。

<!--结果集映射-->
<resultMap id="UserMap" type="User"><!--column数据库的字段,property实体类的属性--><result column="id" property="id"/><result column="name" property="name"/><result column="pwd" property="password"/>
</resultMap><select id="getUserById" resultMap="UserMap">select id, name, pwdfrom mybatis.userwhere id = #{id}
</select>

6、日志

6.1 日志工厂

如果一个数据库操作出现了异常,我们需要排错。日志就是最好的助手!

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

6.2 Log4j

什么是Log4j?

  • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件

  • 我们也可以控制每一条日志的输出格式;

  • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。

  • 可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。

1.导入Log4j依赖

<!--Log4j依赖-->
<dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version>
</dependency>

2.在resources文件夹下建立log4j.properties文件进行配置

#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger = DEBUG,console ,file#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold = DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern =  [%c]-%m%n#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File = ./log/kuang.log
log4j.appender.file.MaxFileSize = 10mb
log4j.appender.file.Threshold = DEBUG
log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern = [%p][%d{yy-MM-dd}][%c]%m%n#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

3.在mybatis-config.xml核心配置文件中,配置log4j为日志的实现!

<!--配置Log4j为日志的实现-->
<settings><setting name="logImpl" value="Log4j"/>
</settings>

简单使用

在要使用Log4j的测试类中,导入包import org.apache.log4j.Logger; 日志对象,参数为当前类的class

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

日志级别

        logger.info("info:进入了testLog4j");logger.debug("DEBUG:进入了testLog4j");logger.error("erro:进入了testLog4j");

7、分页

7.1 使用Limit分页

语法:SELECT * from user limit startIndex,pageSize

使用Mybatis实现分页,核心SQL

1.接口

//使用分页查询数据
List<User> getUserByLimit(Map<String,Integer> map);

2.mapper.xml

<select id="getUserByLimit" parameterType="map" resultType="user">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<>();map.put("startIndex",1);map.put("pageSize",2);List<User> userList = mapper.getUserByLimit(map);for (User user : userList) {System.out.println(user);}sqlSession.close();
}

7.2 RowBounds分页

不再使用SQL实现分页

1.接口

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

2.Mapper.xml

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

3.测试

 @Testpublic void getUserByRowBounds() {SqlSession sqlSession = MybatisUtils.getSqlSession();//RowBounds实现RowBounds rowBounds = new RowBounds(1, 2);List<User> userList = sqlSession.selectList("com.hui.dao.UserMapper.getUserByRowBounds",null,rowBounds);for (User user : userList) {System.out.println(user);}sqlSession.close();}

8、使用注解开发

8.1 注解开发

1.注解在接口上

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

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

<!--绑定接口-->
<mappers><mapper class="com.hui.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();
}

8.2 CRUD

  1. 在MybatisUtils工具类创建的时候实现自动提交事务!

public static SqlSession getSqlSession() {//开启自动提交事务return sqlSessionFactory.openSession(true);
}

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 getUpdateUser(User user);@Delete("delete from user where id =#{uid}")int deleteUser( int id);}

3.测试类

注意:我们必须要将接口绑定到我们的核心配置文件中

关于@Param()注解

  • 基本类型的参数或者String类型,需要加上

  • 引用类型不需要加

  • 如果只有一个基本类型的话,可以忽略,但是建议都加上!

  • 我们在SQL中引用的就是我们这里的@Param("")中设定的属性名!

9、Lombok(偷懒的话可以使用)

使用步骤:

  1. 在IDEA中安装Lombok插件!

  2. 在项目pom.xml文件中导入Lombok的jar包

    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.10</version></dependency>

3.实体类添加注解

@Data //无参构造、get、set、toString、hashCode、equals
@AllArgsConstructor
@NoArgsConstructor
public class User {private int id;private String name;private String password;}

10、多对一处理

10.1 多对一:

  • 多个学生,对应一个老师

  • 对于学生而言,关联多个学生,关联一个老师【多对一】

  • 对于老师而言,集合一个老师,有很多个学生【一对多】

CREATE TABLE `teacher` (`id` INT(10) NOT NULL,`name` VARCHAR(30) DEFAULT NULL,PRIMARY KEY (`id`)
)ENGINE = INNODB DEFAULT CHARSET=utf8INSERT 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=utf8INSERT 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');

10.2 测试环境搭建

  1. 导入Lombok

  2. 新建实体类Teacher,Student

  3. 建立Mapper接口

  4. 建立Mapper.XML文件

  5. 在核心配置文件中绑定注册我们的Mapper接口或者文件!【方式很多,随心选】

  6. 测试查询是否能够成功!

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

<mapper namespace="com.hui.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 teacherwhere id = #{id};</select>
</mapper>

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

<!--按照结果嵌套处理-->
<select id="getStudent2" resultMap="studentTeacher2">select s.id sid, s.name sname, t.name tname,t.id tidfrom student s,teacher twhere 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="id" column="tid"/><result property="name" column="tname"/></association>
</resultMap>

11、一对多处理

比如:一个老师对应多个学生,

对于老师而言就是一堆多关系!

11.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;
}
​

11.2 按照结果嵌套处理

<!--按结果嵌套查询-->
<select id="getTeacherById" resultMap="TeacherStudent">select s.id sid, s.name sname, t.name tname, t.id tidfrom student s,teacher twhere s.tid = t.idand t.id = #{tid}
</select>
​
<resultMap id="TeacherStudent" type="teacher"><result property="id" column="tid"/><result property="name" column="tname"/><!--复杂的属性需要单独处理对象:association集合: collectionjavaType:指定属性的类型ofType:集合中的泛型信息--><collection property="students" ofType="Student"><result property="id" column="sid"/><result property="name" column="sname"/><result property="tid" column="tid"/></collection>
</resultMap>

11.3 按照查询嵌套处理

<!--按照查询嵌套处理-->
<select id="getTeacherById2" resultMap="TeacherStudent2">select *from 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 studentwhere tid = #{tid};
</select>

小结

  • 关联-association【多对一】

  • 集合-collection【一对多】

12、动态SQL

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

根据不同条件拼接 SQL 语句很痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。

12.1 搭建环境

CREATE TABLE `blog`(`id` VARCHAR(50) NOT NULL COMMENT '博客id',`title` VARCHAR(100) NOT NULL COMMENT '博客标题',`author` VARCHAR(30) NOT NULL COMMENT '博客作者',`create_time` DATETIME NOT NULL COMMENT '创建时间',`views` INT(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8
​
  1. 导包

  2. 编写配置文件

  3. 编写实体类

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

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

12.2 IF

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

12.3 choose (when, otherwise)

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

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

12.4 trim (where, set)

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

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

set 元素会动态地在行首插入 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>
​

12.5 SQL片段

有的时候我们需要将功能一小部分抽取出来方便复用

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

<sql id="if-title-author"><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="blog">select * from blog
<where><include refid="if-title-author"></include>
</where>
</select>
​

12.6 Foreach

动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)

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

<select id="queryBlogForeach" parameterType="map" resultType="blog">select * from blog<where><foreach collection="ids" item="id" open="and (" close=")" separator="or">id=#{id}</foreach></where>
</select>

13、缓存

13.1 简介

存储在内存的临时数据

一次查询的结果可以给暂存到一个可以直接取到的地方

减少和数据库的交互 提高性能系统效率

经常查询不经常使用的数据使用缓存

13.2 一级缓存

一级缓存也叫本地缓存 是sqlSession级别的

测试步骤:

1.开启日志

<!--配置Log4j为日志的实现-->
<settings><setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

2.测试一个Session中查询两次相同记录

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

3.查看日志输出

Opening JDBC Connection
Created connection 1739876329.
==>  Preparing: select * from user where id = ?
==> Parameters: 1(Integer)
<==    Columns: id, name, pwd
<==        Row: 1, 阿辉, 123456
<==      Total: 1
User(id=1, name=阿辉, pwd=123456)
================================================================
User(id=1, name=阿辉, pwd=123456)
true
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@67b467e9]
Returned connection 1739876329 to pool.

4.缓存失效的情况

1.查询不同的东西

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

3.手动清理缓存

@Test
public void test() {SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);User user = mapper.queryUserById(1);System.out.println(user);//增删改操作可能会改变原来的数据,所以必定会刷新缓存!//mapper.updateUser(new User(2,"aaaa","bbbb"));//手动清理缓存sqlSession.clearCache();System.out.println("======================");User user2 = mapper.queryUserById(1);System.out.println(user2);System.out.println(user == user2);sqlSession.close();
}

13.3 二级缓存

作用域高点 基于namespace

会话关闭 一级缓存中的东西会保存在二级缓存中

步骤:

1.开启全局缓存

<!--全局性地开启或关闭所有映射器配置文件中已配置的任何缓存-->
<setting name="cacheEnabled" value="true "/>

2.在mapper文件中添加 <cache/>

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

3.把缓存用起来

<select id="queryUserById" resultType="user" useCache="true">

Mybatis笔记(狂神)相关推荐

  1. mybatis笔记之一次插入多条数据sql语句写法

    mybatis笔记之一次插入多条数据sql语句写法

  2. MyBatis笔记二:配置

    MyBatis笔记二:配置 1.全局配置 1.properites 这个配置主要是引入我们的 properites 配置文件的: <properties resource="db.pr ...

  3. 传智_Springmvc+Mybatis由浅入深全套视频教程(燕青)-mybatis笔记(两天)(2017年8月5日16:09:55)

    专业实习消耗了半个月,学习进度一度停滞.mybatis基本的使用不难,和hibernate相比各有优势吧,不是一个风格的框架. mybatis笔记整理如下: 笔记链接:http://download. ...

  4. 【狂神JAVA】MyBatis笔记

    简介 自学的[狂神JAVA]MyBatis 分享自写源码和笔记,希望对大家有帮助 本人配置 jdk13.0.2 (jdk1.7以上均可) Maven 3.6.3 MySQL 5.7.23 (mysql ...

  5. 【狂神说Java】Mybatis笔记

    Mybatis01:Mybatis简介 1.什么是MyBatis MyBatis 是一款优秀的持久层框架,它支持自定义 SQL.存储过程以及高级映射. MyBatis 免除了几乎所有的 JDBC 代码 ...

  6. 狂神说-Mybatis笔记(总)

    环境: JDK1.8 MySQL 8.0.23 maven 3.6.1 IDEA2020.3 框架:需要配置文件 官方中文文档:https://mybatis.org/mybatis-3/zh/ind ...

  7. 【狂神Mybatis笔记】配置解析

    核心配置文件:mybatis-config.xml Mybatis的配置文件包含了会影响Mybatis行为的设置和属性信息 环境配置(environments) 要求:学会使用配置多套运行环境 MyB ...

  8. 【狂神MyBatis笔记】map作为参数传递类型进行增删改查模糊查询

    接口中的参数传入map: 实现类的传入参数为map的键的名称,这个键可以自定义名称: 例:根据ID获取用户 接口: //根据ID获取用户User getUserById2(Map<String, ...

  9. Mybatis学习(狂神)

    文章目录 前言 1. Mybatis简介 1.1.什么是MyBatis 1.2 .持久化 1.3.持久层 1.4.为什么需要Mybatis 2.MyBatis第一个程序 2.1.源码演示 2.2.可能 ...

  10. 【MyBatis笔记】04-插入操作更新操作删除操作

    保存更新删除 插入操作 获取插入的最后一个id 更新操作 删除操作 查询操作在之前的笔记中~ 插入操作 映射文件 Customer.xml : 插入数据的标签为 insert,与查询 select 区 ...

最新文章

  1. 第章量子计算机产业,又一个世界第一,九章量子计算机诞生,中国战斗机智能空战不是梦...
  2. C++ Primer第18章Vector的再实现及bug修正
  3. 什么是Linux系统调用system call?(Linux内核中设置的一组用于实现各种系统功能的子程序)(区别于标准C库函数调用)核心态和用户态的概念、中断的概念、系统调用号、系统调用表
  4. python 的案例实战_python案例实战之一
  5. 【openMV】算法矫正镜头+视频格式对应的分辨率
  6. 2012、12、17
  7. 【Prescan学习】Prescan环境配置(介绍+安装+学习资源)
  8. 【尚硅谷】Gradle教程入门到进阶(从gradle安装到项目实战)笔记
  9. 4、SYN-RCVD
  10. uploadify上传文件在360浏览器急速模式下失败
  11. HDU 2246 神题?一千多行
  12. 世纪三部曲(全9册) 读后感
  13. 1698无法登录mysql服务器_一,问题描述:MysqlERROR1698(28000)解决,新装了mysql-server-5.7,登录为这一问题,普通用户不能进mysql,只有root用...
  14. 自动控制原理实验一——离散控制系统建模和仿真
  15. JavaScript——leetcode2006 差的绝对值为k的数对数目
  16. 自写小小工具解密FeiQ消息
  17. 大学图书馆图书借阅管理系统
  18. JVM基础 之Java HotSpot虚拟机中的内存管理
  19. 6个找到用户痛点的产品方向
  20. 一度智信 | 教你拼多多主图的制作

热门文章

  1. 微信测试是否被删软件,拒绝好友测试!教你在对方不知情下如何查看是否被微信好友删除...
  2. 未来是否繁花似锦,源自我们当下之努力
  3. SPSS作业-卡方检验-列联表
  4. Excel数据透视表:查看数据的频率分布
  5. C语言平年闰年该月天数,2. 输入年月日,求它是该年的第几天。注:闰年的2月有29天,平年的2月有28天。(C语言编程题)...
  6. 手把手教你软件著作权申请(全流程)(不花一分冤枉钱)
  7. vue项目之微信分享
  8. HTML5期末大作业:爱宠之家网站设计——蓝色版爱宠之家(5页) 致热爱动物网页设计作品 大学生爱宠专题网页设计作业模板 动物静态HTML网页模板下载
  9. 打印参数量GFLOPs等的参考链接暂存+pycocotools安装
  10. Segger和Micrium之间的区别和联系