Mybatis_狂神(XML和注解,配置,lombok,动态sql,缓存等)
狂神说Mybatis视频链接:
B站视频
Mybatis官方文档:
MyBatis
1、简介
1.1 什么是Mybatis
- MyBatis 是一款优秀的持久层框架; 持久层即dao层
- 它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis可以通过简单的 XML或注解,来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
1.2 持久化
1.3 持久层
Dao层、Service层、Controller层,持久层即Dao层
1.4 为什么需要MyBatis
帮助程序员将数据存入到数据库中
方便
传统的JDBC代码太复杂了,简化,框架,自动化
不用MyBatis也可以,技术没有高低之分
优点:
- 简单易学
- 灵活
- sql和代码的分离,提高了可维护性。
- 提供映射标签,支持对象与数据库的orm字段关系映射
- 提供对象关系映射标签,支持对象关系组建维护
- 提供xml标签,支持编写动态sql
2、第一个Mybatis程序
思路:搭建环境 --> 导入MyBatis --> 编写代码 --> 测试
2.1 搭建环境
2.删除src目录 (就可以把此工程当做父工程了,然后创建子工程)
<!--导入依赖-->
<dependencies><!--mysqlq驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.12</version></dependency><!--mybatis--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.4</version></dependency><!--junit--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency>
</dependencies>
2.2 创建一个模块
<?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核心配置文件-->
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/>//最好在URL中设置时区,要不idea也会提示设置时区<property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/><property name="username" value="root"/><property name="password" value="root"/></dataSource></environment></environments>
<!--每一个Mapper.xml都需要在mybatis核心配置文件中注册!--><mappers><mapper resource="com/yff/dao/UserMapper.xml"/></mappers>
</configuration>
注意点:驱动driver:com.mysql.jdbc.Driver和com.mysql.cj.jdbc.Driver的区别
com.mysql.jdbc.Driver 是 mysql-connector-java 5中的,
com.mysql.cj.jdbc.Driver 是 mysql-connector-java 6中的
//sqlSessionFactory --> sqlSession
public class MybatisUtils {static SqlSessionFactory sqlSessionFactory = null;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 命令所需的所有方法。SqlSession相当于jdbc中的statement和PreparedStatementpublic static SqlSession getSqlSession(){return sqlSessionFactory.openSession(); //sqlSessionFactory.openSession(true):开启自动提交事务,不用commit了,mybatis默认未开启自动提交事务 }
}
2.3 编写代码
实体类
package com.yff.pojo;public class User {private int id;private String name;private String pwd;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;}public User() {}@Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + '\'' +", pwd='" + pwd + '\'' +'}';}
}
Dao接口
public interface UserDao {public List<User> getUserList();
}
- 接口实现类 (由原来的UserDaoImpl转变为一个Mapper配置文件,之前是应该写UserDao的实现类了)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--namespace=绑定一个指定的Dao/Mapper接口;id绑定实现的接口的方法;resultType绑定返回的类型(泛型,指List<User>中的User,且需要全路径(编译后target中classes下的全路径))。
全限定名(比如 “com.mypackage.MyMapper.selectAllThings)将被直接用于查找及使用。这里尽量使用全限定名。
-->
<mapper namespace="com.kuang.dao.UserDao"><select id="getUserList" resultType="com.kuang.pojo.User">select * from USER</select>
</mapper>
- 使用junit测试(1、测试代码最好和工程代码层级一致 2、执行sql的方式一是重点,方式二已基本不用)
代码:
package com.yff.dao;import com.yff.pojo.User;
import com.yff.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import java.util.List;public class UserDaoTest {@Testpublic void test(){SqlSession sqlSession = null;try {//第一步 获取sqlsession对象sqlSession = MybatisUtils.getSqlSession();//第二步: 方式1: getmMpper执行sqlUserDao userdao = sqlSession.getMapper(UserDao.class);List<User> userList = userdao.getUserList();//第二步: 方式2: 指定执行sql
// List<User> userList = sqlSession.selectList("com.yff.dao.UserDao.getUserList");for (User user : userList) {System.out.println(user);}}catch (Exception e){e.printStackTrace();}finally {//关闭sqlsessionsqlSession.close();}}
}
结果:
可能会遇到的执行问题:
1.配置文件没有注册
报错:
org.apache.ibatis.binding.BindingException: Type interface com.kuang.dao.UserDao is not known to the MapperRegistry.MapperRegistry是什么?
核心配置文件中注册mappers
2.绑定接口错误
3.方法名不对
4.返回类型不对
5.Maven导出资源问题
<build><resources><resource><directory>src/main/java</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource></resources></build>
3、CURD和万能map、模糊查询
3.1. namespace
namespace中的包名要和Dao/Mapper接口的包名一致,需要全限定名
3.2. select
1:如果只是查询一个字段,用String类型就可以,resultType="String";
2:如果是多个字段,可以用相关的类名作为返回类型,例如 你的monitor_entity表对应的实体类为Monitor,
就可以这样写:resultType="Monitor";
3:解决实体类属性名和数据库字段名不一致的问题用resultMap
3.3. Insert
使用useGeneratedKeys="true" keyProperty="userId"可以在user对象中返回userId
<insert id="insertUser" parameterType="SysUser" useGeneratedKeys="true" keyProperty="userId">insert into sys_user(<if test="userId != null and userId != 0">user_id,</if><if test="deptId != null and deptId != 0">dept_id,</if><if test="userName != null and userName != ''">user_name,</if><if test="nickName != null and nickName != ''">nick_name,</if><if test="email != null and email != ''">email,</if><if test="avatar != null and avatar != ''">avatar,</if><if test="phonenumber != null and phonenumber != ''">phonenumber,</if><if test="sex != null and sex != ''">sex,</if><if test="password != null and password != ''">password,</if><if test="status != null and status != ''">status,</if><if test="createBy != null and createBy != ''">create_by,</if><if test="remark != null and remark != ''">remark,</if><if test="shipIMONo != null and shipIMONo != ''">ship_imo_no,</if>create_time)values(<if test="userId != null and userId != ''">#{userId},</if><if test="deptId != null and deptId != ''">#{deptId},</if><if test="userName != null and userName != ''">#{userName},</if><if test="nickName != null and nickName != ''">#{nickName},</if><if test="email != null and email != ''">#{email},</if><if test="avatar != null and avatar != ''">#{avatar},</if><if test="phonenumber != null and phonenumber != ''">#{phonenumber},</if><if test="sex != null and sex != ''">#{sex},</if><if test="password != null and password != ''">#{password},</if><if test="status != null and status != ''">#{status},</if><if test="createBy != null and createBy != ''">#{createBy},</if><if test="remark != null and remark != ''">#{remark},</if><if test="shipIMONo != null and shipIMONo != ''">#{shipIMONo},</if>sysdate())</insert>
useGeneratedKeys的详解_小草dym的博客-CSDN博客_usegeneratedkeys
3.4. update
3.5. Delete
id:就是对应的namespace中的方法名;
resultType : Sql语句执行的返回值;
parameterType : 参数类型;
1.编写接口
package com.yff.dao;import com.yff.pojo.User;import java.util.List;public interface UserMapper {//获取用户列表List<User> getUserList();//查询指定用户User getUser(int id);//新增用户int insertUser(User user);//修改用户int updateUser(User user);//删除用户int deleteUser(int id);
}
2.编写对应的mapper中的sql语句
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--命名空间:namespace:绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.yff.dao.UserMapper"><select id="getUserList" resultType="com.yff.pojo.User">select * from user</select><select id="getUser" resultType="com.yff.pojo.User" parameterType="int">select * from user where id=#{id}</select><!--可以通过#{}直接取到对象中的属性--><update id="updateUser" parameterType="com.yff.pojo.User">update user set name = #{name},pwd=#{pwd} where id=#{id}</update><insert id="insertUser" parameterType="com.yff.pojo.User">insert into user values(#{id},#{name},#{pwd});</insert><delete id="deleteUser" parameterType="int" >delete from user where id = #{id}</delete>
</mapper>
3.测试
package com.yff.dao;import com.yff.pojo.User;
import com.yff.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import java.util.List;public class UserMapperTest {@Testpublic void test(){//第一步获取sqlsession对象SqlSession sqlSession = null;try {sqlSession = MybatisUtils.getSqlSession();//第二步: 方式1: getmMpper执行sqlUserMapper userdao = sqlSession.getMapper(UserMapper.class);List<User> userList = userdao.getUserList();//第二步: 方式2: 指定执行sql
// List<User> userList = sqlSession.selectList("com.yff.dao.UserDao.getUserList");for (User user : userList) {System.out.println(user);}}catch (Exception e){e.printStackTrace();}finally {//关闭sqlsessionsqlSession.close();}}@Testpublic void getUserTest(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);User user = mapper.getUser(1);System.out.println(user);sqlSession.close();}@Testpublic void updateUserTest(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);int i = mapper.updateUser(new User(1, "test", "12345"));if (i>0){System.out.println("更新ok");}sqlSession.commit();sqlSession.close();}@Testpublic void insertUserTest(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);int i = mapper.insertUser(new User(9, "liu", "8888"));if (i > 0) {System.out.println("插入ok");}sqlSession.commit();sqlSession.close();}@Testpublic void deleteUserTest(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);int i = mapper.deleteUser(3);if (i > 0) {System.out.println("删除ok");}sqlSession.commit();sqlSession.close();}
}
注意:增删改查一定要提交事务(mybatis默认未开启自动提交事务):
sqlSession.commit();
3.6. 万能Map(用作接口传参)
假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应该考虑使用Map!
----------------------------------------int insertUser(User user);
----------------------------------------<insert id="insertUser" parameterType="com.yff.pojo.User">insert into user(id,pwd) values(#{id},#{pwd});</insert>
----------------------------------------//传全部参数,因为构造方式只有无参和全部参数,这样不会报错,#{}只会取用到的 @Testpublic void insertUserTest(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);int i = mapper.insertUser(new User(99, "meiren","8888"));if (i > 0) {System.out.println("插入ok");}sqlSession.commit();sqlSession.close();}
--------------------------------------------
//传部分参数,new User时会报错没有构造方法,需要补充构造方法@Testpublic void insertUserTest(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);int i = mapper.insertUser(new User(100, "8888")); //new User(100, "8888")报错,需要补充构造方法if (i > 0) {System.out.println("插入ok");}sqlSession.commit();sqlSession.close();}
//用万能Map插入用户
int insertUserMap(Map<String,Object> map);
<!--对象中的属性可以直接取出来 传递map的key--><insert id="insertUserMap" parameterType="map">insert into user(id,name) values(#{idyff},#{nameyff});</insert>
@Testpublic void testMap(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);Map<String, Object> map = new HashMap<String,Object>();map.put("idyff",10);map.put("nameyff","吴彦祖");int i = mapper.insertUserMap(map);if (i > 0) {System.out.println("插入成功");}sqlSession.commit();sqlSession.close();}
<sql id="selectConfigVo">select config_id, config_name, config_key, config_value, config_type, create_by, create_time, update_by, update_time, remark from sys_config</sql><!-- 查询条件 --><sql id="sqlwhereSearch"><where><if test="configId !=null">and config_id = #{configId}</if><if test="configKey !=null and configKey != ''">and config_key = #{configKey}</if></where></sql> <select id="selectConfig" parameterType="SysConfig" resultMap="SysConfigResult"><include refid="selectConfigVo"/><include refid="sqlwhereSearch"/></select>SysConfig是实体类
@Overridepublic SysConfig selectConfigById(Long configId){SysConfig config = new SysConfig();config.setConfigId(configId); (set查询条件的字段)return configMapper.selectConfig(config); (重点)}
Map传递参数,直接在sql中取出key即可! 【parameterType=“map”】
对象传递参数,直接在sql中取出对象的属性即可! 【parameterType=“Object”】
只有一个基本类型参数的情况下,可以直接在sql中取到 【parameterType="_int"】
万能map是一个办法,实际工作中通过bean入参也用的很多。
备注:前端到controller解析的参数传递,详见自己博客:
springMVC_狂神_02_配置版和注解版编码、restful风格、数据跳转、Json处理(重点)_keep one's resolveY的博客-CSDN博客
3.8. 模糊查询
List<User> userList = mapper.getUserLike("%李%");
select * from 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
MyBatis 可以配置成适应多种环境,default就代表当前环境
<environments default="test"><environment id="development">....</environment><environment id="test">....</environment>
</environments>
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境
MyBatis默认的事务管理器就是JDBC ,连接池:POOLED
<?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><!--引入外部配置文件--><properties resource="db.properties"></properties><!-- <properties resource="db.properties"/> 推荐使用自闭合/ --><environments default="development"><environment id="development"><transactionManager type="JDBC"/> //事务管理器,一般使用jdbc,有2种:JDBC | MANAGED<dataSource type="POOLED"> //连接池,一般使用pooled,有3种:UNPOOLED|POOLED|JNDI<property name="driver" value="${driver}"/> //通过${}获取properties文件中的配置<property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/></dataSource></environment></environments><!--每一个Mapper.xml都需要在mybatis核心配置文件中注册!--><mappers><mapper resource="com/yff/dao/UserMapper.xml"/></mappers>
</configuration>
4.3. 属性 properties
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。【db.poperties】
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username=root
password=123
<properties resource="db.properties"/> 后通过${}获取
2.可以在其中增加一些属性配置,eg:增加username和pwd
3.如果两个文件有同一个字段,优先使用外部配置文件的,eg:
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username=root
password=root
----------------------------------------------
4.备注:mybatis-config.xml核心配置文件中,标签是有顺序的,必须遵守:
-----------------------------------------------
4.4. 类型别名 typeAliases
类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置.
意在降低冗余的全限定类名书写。
第一种:给实体类起别名
<!--可以给实体类起别名-->
<typeAliases><typeAlias type="com.kuang.pojo.User" alias="User"/>
</typeAliases>
第二种:指定一个包,每一个在包 com.kuang.pojo 中的 Java Bean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。 比如 com.kuang.pojo.User 的别名为 user,;这是官方文档推荐的,用这种方式的话类的开头字母要使用小写,但是使用User(大写)测试后其实也是可以的
<typeAliases><package name="com.kuang.pojo"/>
</typeAliases>
若有注解,则别名为其注解值。见下面的例子:
@Alias("hello")
public class User{...
}
在实体类比较少的时候,使用第一种方式。
如果实体类十分多,建议用第二种扫描包的方式。
第一种可以自定义别名,第二种不行,如果非要改,需要在实体上增加注解。
注意:下面是一些为常见的 Java 类型内建的类型别名。它们都是不区分大小写的,注意,为了应对原始类型的命名重复,采取了特殊的命名风格。
别名 映射的类型
_byte byte
_long long
_short short
_int int
_integer int
_double double
_float float
_boolean boolean
string String
byte Byte
long Long
short Short
int Integer
integer Integer
double Double
float Float
boolean Boolean
date Date
decimal BigDecimal
bigdecimal BigDecimal
object Object
map Map
hashmap HashMap
list List
arraylist ArrayList
collection Collection
iterator Iterator
4.5. 设置 Settings
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。(官网设置Settings有全面解释:mybatis – MyBatis 3 | 配置)
4.6. 其他配置(了解即可)
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins 插件
- mybatis-generator-core
- mybatis-plus
- 通用mapper
4.7. 映射器 mappers
MapperRegistry:注册绑定我们的Mapper文件;
<!--每一个Mapper.xml都需要在MyBatis核心配置文件中注册-->
<mappers><mapper resource="com/kuang/dao/UserMapper.xml"/>
</mappers>
<!--每一个Mapper.xml都需要在MyBatis核心配置文件中注册-->
<mappers><mapper class="com.kuang.dao.UserMapper"/>
</mappers>
<mappers><package name="com.kuang.dao"/>
</mappers>
4.8. 作用域和生命周期
声明周期和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题。
一旦创建了SqlSessionFactory,就不再需要它了
局部变量
SqlSessionFactory:
说白了就可以想象为:数据库连接池
SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建一个实例。
因此SqlSessionFactory的最佳作用域是应用作用域(ApplocationContext)。
最简单的就是使用单例模式或静态单例模式。
SqlSession:
- 连接到连接池的一个请求
- SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
- 用完之后需要赶紧关闭,否则资源被占用!
其中的每一个mapper都是代表的一个具体的业务(增删改查)
5、解决实体类属性名和数据库字段名不一致的问题(和10关联起来看)
数据库中的字段
新建一个项目,拷贝之前的,测试实体类字段不一致的情况
// select * from user where id = #{id}
或
// select id,name,pwd from user where id = #{id}
<select id="getUserById" resultType="com.kuang.pojo.User">select id,name,pwd as password from USER where id = #{id}
</select>
5.2. resultMap(解决方法2即是使用resultMap)
id name pwd
id name password
<!--结果集映射-->
<resultMap id="UserMap" type="User"><!--column数据库中的字段,property实体类中的属性--><result column="id" property="id"></result><result column="name" property="name"></result><result column="pwd" property="password"></result>
</resultMap><select id="getUserList" resultMap="UserMap">select * from USER
</select>
ResultMap 元素是 MyBatis 中最重要最强大的元素。
ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
ResultMap 的优秀之处——你完全可以不用显式地配置它们。
resultMap的作用(工作中必用)
<resultMap>标签用于封装sql的查询结果,可以包装成一个简单POJO对象,也可以包装成我们自定义的对象,只要我们使用<result>子标签指定好查询结果的列和对象的属性之间的对应关系就好了。
官方原因
说是用于提高性能,但是在一些情况下,没有Id的话结果会出错。
官方doc传送门(中文):https://mybatis.org/mybatis-3/zh/sqlmap-xml.html
博客:MyBatis <resultMap>中的<id>的作用到底是什么? - 简书
6、日志
6.1 日志工厂
如果一个数据库操作,出现了异常,我们需要排错,日志就是最好的助手!
- SLF4J
- LOG4J 【掌握】
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING 【掌握】
- NO_LOGGING
在MyBatis中具体使用哪一个日志实现,在设置中设定
<settings>//标准的日志工厂<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
6.2 Log4j
Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件;
我们也可以控制每一条日志的输出格式;
通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程;
最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
1.先导入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/yff.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.sq1.PreparedStatement=DEBUG
3.配置settings为log4j实现
<settings><setting name="logImpl" value="LOG4J"/></settings>
4.直接测试运行
Log4j简单使用
1.在要使用Log4j的类中,导入包 import org.apache.log4j.Logger;
2.日志对象,参数为当前类的class对象
Logger logger = Logger.getLogger(UserDaoTest.class);
3.日志级别:分为OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL或者您定义的级别。Log4j建议只使用四个级别,优 先级从高到低分别是ERROR、WARN、INFO、DEBUG
@Testpublic void testLog4j() {logger.info("info日志");logger.debug("debug日志");logger.warn("warn日志");logger.error("error日志");try {int i = 1;int y = 0;int z = i / y;} catch (Exception e) {logger.error(e);}}
7、分页
思考:为什么分页?
- 减少数据的处理量
7.1 使用Limit分页
SELECT * from user limit startIndex,pageSize
//分页
List<User> getUserByLimit(Map<String,Integer> map);
<!--分页查询-->
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">select * from user limit #{startIndex},#{pageSize}
</select>
@Testpublic 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> list = mapper.getUserByLimit(map);for (User user : list) {System.out.println(user);}}
7.2 RowBounds分页
//分页2
List<User> getUserByRowBounds();
<!--分页查询2--><select id="getUserListRowBounds" resultMap="UserMap">select * from user;</select>
public void getUserByRowBounds(){SqlSession sqlSession = MybatisUtils.getSqlSession();//RowBounds实现RowBounds rowBounds = new RowBounds(1, 2);//通过Java代码层面RowBounds实现分页 RowBounds依赖sqlSession.selectList第二种实现执行sqlList<User> userList = sqlSession.selectList("com.kaung.dao.UserMapper.getUserByRowBounds", null, rowBounds);for (User user : userList) {System.out.println(user);}sqlSession.close();}
7.3 分页插件
8、使用注解开发
8.1 面向接口开发
- 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性和方法;
- 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现;
- 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题,更多的体现就是对系统整体的架构;
8.2 mybatis使用注解
选择何种方式来配置映射,以及认为是否应该要统一映射语句定义的形式,完全取决于你和你的团队。 换句话说,永远不要拘泥于一种方式,你可以很轻松的在基于注解和 XML 的语句映射方式间自由移植和切换。
sql 类型主要分成 :
@select ()
@update ()
@Insert ()
@delete ()
1.注解在接口上实现
@Select("select * from user")
List<User> getUsers();
2.必须在核心配置文件中绑定接口
<mappers><mapper class="com.kuang.dao.UserMapper"/>
</mappers>
3.测试
@Test public void testGetAllUser() { SqlSession session = MybatisUtils.getSession();//本质上利用了jvm的动态代理机制 UserMapper mapper = session.getMapper(UserMapper.class);List<User> users = mapper.getUsers(); for (User user : users){System.out.println(user);}session.close();
}
session.getMapper(UserMapper.class);本质:反射机制实现
mybatis底层:动态代理
MyBatis详细执行流程
8.3 mybatis注解CURD
//编写接口,增加注解
-------------------------------------------------------
public interface UserMapper {//查询指定用户@Select("select * from user")List<User> getUser();//查询指定用户@Select("select * from user where id =#{id} and name =#{name}")User getUser1(@Param("id") int id,@Param("name") String name);//更新@Update("update user set pwd =#{password}, name=#{name} where id =#{id}")int updateUser(User user);//插入@Insert("insert into user values(#{id},#{name},#{paaword})")int insertUser(User user);//删除@Delete("delete from user where id=#{uid}")int deleteUser(@Param("uid") int id);
}//测试
----------------------------------------------------------public class UserMapperTest {static Logger logger = Logger.getLogger(UserMapperTest.class);@Testpublic void getUserTest(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);User u = mapper.getUser1(1, "test");System.out.println(u);sqlSession.close();}@Testpublic void getUserTest1(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);int num = mapper.updateUser(new User(99, "yyy", "9999"));System.out.println(num);sqlSession.close();}
}
- @Param("xx")只是针对基本类型,引用类型不需要
- 如果只有一个基本类型的话,可以忽略,但是建议大家都加上
- @Param("uid")和sql中#{uid}必须对应一致,且以@Param为准,我们在SQL中引用的就是我们这里的@Param()中设定的属性名,sql中通过#{} 或 ${}的方式引用
- 方法存在多个参数,所有的参数前面必须加上@Param("id")注解
- 通过#{} 或 ${}可以直接取到参数对象中的属性
- 使用mybatis时,我们在不使用mybatis注解开发时,也可以在接口中使用@Param( )注解,也遵守上面的规则
- 当接口中只有一个参数(并且没有用@Param())时候,需要在xml中添加响应的参数类型parameterType;
如果是多个参数(每个参数都是用@Param())的时候,就不会去读参数类型parameterType,
直接取得参数里面的值。
#{}和${}区别,#{}可以防止sql注入,尽量使用#{}
https://blog.csdn.net/weixin_45433031/article/details/123208290
9、Lombok
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.10</version><scope>provided</scope>
</dependency>
@EqualsAndHashCode 注解:
1. 此注解会生成equals(Object other) 和 hashCode()方法。
2. 它默认使用非静态,非瞬态的属性
3. 可通过参数exclude排除一些属性
4. of 用来指明你要用什么字段来重写equals和hashcode
5. 它默认仅使用该类中定义的属性且不调用父类的方法
6. 可通过callSuper=true解决上一点问题。让其生成的方法中调用父类的方法。callSuper 这个选项只能用在有父类情况下,如上图如果没有Father那么会报错。默认是false,当改成true后,会调用父类的equals方法通过官方文档,可以得知,当使用@Data注解时,则有了@EqualsAndHashCode注解,那么就会在此类中存在equals(Object other) 和 hashCode()方法,且默认不会使用父类的属性,这就导致了可能的问题。
比如,有多个类有相同的部分属性,把它们定义到父类中,恰好id(数据库主键)也在父类中,那么就会存在部分对象在比较时,它们并不相等,却因为lombok自动生成的equals(Object other) 和 hashCode()方法判定为相等,从而导致出错。修复此问题的方法很简单:
1. 使用@Getter @Setter @ToString代替@Data并且自定义equals(Object other) 和 hashCode()方法,比如有些类只需要判断主键id是否相等即足矣。
2. 或者使用在使用@Data时同时加上@EqualsAndHashCode(callSuper=true)注解。
举例:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {private int id;private String name;private String password;
}
10、多对一处理(和5关联起来看)
(多对一和一对多处理,本质还是解决实体类属性名和数据库字段名不一致的问题,是resultmap的使用进阶)
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');
多个学生一个老师;
alter table student ADD CONSTRAINT fk_tid foreign key (tid) references teacher(id)
10.1. 测试环境搭建
1.导入lombok
2.新建实体类Teacher,Student
----------------------------
package com.yff.pojo;
import lombok.Data;@Data
public class Student {private int id;private String name;//学生需要关联一个老师private Teacher teacher;
}-----------------------------
package com.yff.pojo;
import lombok.Data;@Data
public class Teacher {private int id;private String name;
}
public interface StudentMapper {//查询所有学生信息及对应的老师的信息1(子查询实现)List<Student> getStudent1();//查询所有学生信息及对应的老师的信息1(联表查询实现)List<Student> getStudent2();
}
4.建立Mapper.xml文件
5.在核心配置文件中绑定注册我们的Mapper接口或者文件 【方式很多,随心选】
<?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><!--引入外部配置文件--><properties resource="db.properties"></properties><!--<properties resource="db.properties"/> 推荐使用自闭合--><settings><setting name="logImpl" value="LOG4J"/></settings><!--全限定名-别名--><typeAliases><package name="com.yff.pojo"/><!--<typeAlias type="com.yff.pojo.User" alias="users"/>--></typeAliases><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><mappers><mapper class="com.yff.dao.TeacherMapper"/><mapper class="com.yff.dao.StudentMapper"/></mappers>
</configuration>
10.2. 按照查询嵌套处理(子查询)
<!--思路:1. 查询所有的学生信息2. 根据查询出来的学生的tid寻找特定的老师 (子查询)-->
<select id="getStudent" resultMap="StudentTeacher">select * from student
</select>
<!--column数据库中的字段,property实体类中的属性,要实体类和数据库对应起来看-->
<resultMap id="StudentTeacher" type="student"> //type="student"因为mybatis核心配置文件中有全限定名的别名,并使用指定包<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} //#{id}会自动推断入参为column="tid",所以可以随意写#{xx},但尽量一致写成#{tid}
</select>
10.3.按照结果嵌套处理(联表查询)
<!--按照结果进行查询--><select id="getStudent2" resultMap="StudentTeacher2">select s.id sid , s.name sname, t.name tnamefrom student s,teacher twhere s.tid=t.id //联表查询sql</select><!--结果封装,将查询出来的列封装到对象属性中--><resultMap id="StudentTeacher2" type="student"><result property="id" column="sid"/> //column="sid", sql中有别名时必须使用别名<result property="name" column="sname"/><association property="teacher" javaType="teacher"> //javaType="teacher"因为mybatis核心配置文件中有全限定名的别名<result property="name" column="tname"></result></association></resultMap>
Mybatis多表关联查询的实现(DEMO)_JAVA教程_服务器之家
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;
}
public interface TeacherMapper {//获取指定老师下的所有学生和老师的信息Teacher getTeacher1(@Param("tid") int id);Teacher getTeacher2(@Param("tid") int id);
}
11.2. 按照结果嵌套处理
<!--按结果嵌套查询-->
<select id="getTeacher" resultMap="StudentTeacher">SELECT s.id sid, s.name sname,t.name tname,t.id tid FROM student s, teacher tWHERE s.tid = t.id AND tid = #{tid}
</select>
<resultMap id="StudentTeacher" type="Teacher"><result property="id" column="tid"/><result property="name" column="tname"/><!--复杂的属性,我们需要单独处理 对象:association 集合:collectionjavaType=""指定属性的类型!集合中的泛型信息,我们使用ofType获取因为上面是多对一,多个学生关联一个老师,实体类中是单个对象,使用javaType,而现在一个老师关联多个学生,实体类中属性为List<Student>,所以用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="getTeacher2" resultMap="StudentTeacher2">select * from teacher where id =#{tid};</select><resultMap id="StudentTeacher2" type="teacher"><result property="id" column="id"/><result property="name" column="name"/><collection property="students" javaType="ArrayList" ofType="student" select="getstudentbyteacherId" column="id"/></resultMap><select id="getstudentbyteacherId" resultType="student">select * from student where tid =#{uid}</select>
测试
多对一和一对多也可以这样用:
<mapper namespace="com.oceansite.system.mapper.SysUserMapper"><resultMap type="SysUser" id="SysUserResult"><id property="userId" column="user_id" /><result property="deptId" column="dept_id" /><result property="userName" column="user_name" /><result property="nickName" column="nick_name" /><result property="email" column="email" /><result property="phonenumber" column="phonenumber" /><result property="sex" column="sex" /><result property="avatar" column="avatar" /><result property="password" column="password" /><result property="status" column="status" /><result property="delFlag" column="del_flag" /><result property="loginIp" column="login_ip" /><result property="loginDate" column="login_date" /><result property="createBy" column="create_by" /><result property="createTime" column="create_time" /><result property="updateBy" column="update_by" /><result property="updateTime" column="update_time" /><result property="remark" column="remark" /><result property="signImg" column="image"/><association property="dept" column="dept_id" javaType="SysDept" resultMap="deptResult" /><collection property="roles" javaType="java.util.List" resultMap="RoleResult" /></resultMap><resultMap id="deptResult" type="SysDept"> 多对一<id property="deptId" column="dept_id" /><result property="parentId" column="parent_id" /><result property="deptName" column="dept_name" /><result property="orderNum" column="order_num" /><result property="leader" column="leader" /><result property="status" column="dept_status" /></resultMap><resultMap id="RoleResult" type="SysRole"> 一对多<id property="roleId" column="role_id" /><result property="roleName" column="role_name" /><result property="roleKey" column="role_key" /><result property="roleSort" column="role_sort" /><result property="dataScope" column="data_scope" /><result property="status" column="role_status" /></resultMap>
小结
1.关联 - association 【多对一】
2.集合 - collection 【一对多】
3.javaType & ofType
- JavaType用来指定实体类中的类型
- ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型
注意点:
- 保证SQL的可读性,尽量保证通俗易懂
- 注意一对多和多对一,属性名和字段的问题
- 如果问题不好排查错误,可以使用日志,建议使用Log4j
备注(column有多个参数时怎么办?):
面试高频
- Mysql引擎
- InnoDB底层原理
- 索引
- 索引优化
12、动态SQL
什么是动态SQL:(使用动态标签)所谓的动态sql本质还是sql语句,只是我们在sql层面,执行了逻辑代码,(sql尽量还是标准)
动态SQL就是根据不同的条件生成不同的SQL语句,所谓的动态SQL,本质上还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码
搭建环境并插入数据
vCREATE TABLE `mybatis`.`blog` (`id` int(10) NOT NULL AUTO_INCREMENT COMMENT '博客id',`title` varchar(30) NOT NULL COMMENT '博客标题',`author` varchar(30) NOT NULL COMMENT '博客作者',`create_time` datetime(0) NOT NULL COMMENT '创建时间',`views` int(30) NOT NULL COMMENT '浏览量',PRIMARY KEY (`id`)
)
IF详解:
@Data
public class Blog {private String id;private String title;private String author;private Date createTime; //属性名和字段名不一致,通过setting解决private int views;
}
Mapper.xml文件(IF),注意下面xml可以优化使用where标签,省略where 1=1,实际工作中这么写不好
choose (when, otherwise)详解:
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
下面通过map传了3个参数进行测试,由于是choose (when, otherwise)语句,所以只会执行第一个,查询出title等于"java如此简单"
trim、where、set详解:
where 元素:只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
<select id="findActiveBlogLike"resultType="Blog">SELECT * FROM BLOG<where><if test="state != null">state = #{state}</if><if test="title != null">AND title like #{title}</if><if test="author != null and author.name != null">AND author_name like #{author.name}</if></where>
</select>
set元素:set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)
https://www.jb51.net/article/217277.htm
prefix 字首, prefixOverrides 字首覆盖, suffix后缀, suffixOverrides 后缀覆盖
例如:与 where 元素等价的自定义 trim 元素为:(注意此例中的空格是必要的)
<trim prefix="WHERE" prefixOverrides="AND |OR ">...
</trim>
foreach详解:
List<Blog> queryBlogForeach(Map map);
![](/assets/blank.gif)
![](/assets/blank.gif)
![](/assets/blank.gif)
工作举例:
Integer deleteAlarmRecordByIds(Long[] alarmId); <delete id="deleteAlarmRecordByIds" parameterType="Long">delete from alarm_record where alarm_id in<foreach collection="array" item="alarmId" open="(" separator="," close=")">#{alarmId}</foreach></delete>--------------------------------------------------------------Integer deleteDict(@Param("dictType") String dictType,@Param("shipImo")String shipImo, @Param("dictIds")Long[] dictIds);<delete id="deleteDict">delete from cctv_dict where dict_type = #{dictType} and ship_imo = #{shipImo} and dict_id in<foreach collection="dictIds" item="dictId" open="(" separator="," close=")">#{dictId}</foreach></delete>
sql片段详解:
有的时候,我们可能会将一些公共的sql抽取出来,方便使用!
1.使用SQL标签抽取公共部分
<sql id="if-title-author"><if test="title!=null">title = #{title}</if><if test="author!=null">and author = #{author}</if>
</sql>
2.使用 include 引用sql片段
sql片段扩展:
mybatis xml 文件中对于重复出现的sql 片段可以使用标签提取出来,在使用的地方使用标签引用即可具体用法如下:
<sql id="someSQL">id,name
</sql>
<select id="selectSome" >select<include refid="someSQL"/>from t</select>
在中可以使用${}传入参数,如下:
<sql id="someSQL">${tableName}.id,${tableName}.name
</sql>
<select id="selectSome" >select<include refid="someSQL"><property name="tableName" value="t"/></include>from t</select>
对于多个xml文件需要同时引用一段相同的 可以在某个xml 中定义这个 sql 代码片段,在需要引用的地方使用全称引用即可,例子如下:
ShareMapper.xml
<mapper namespace="com.company.ShareMapper"> <sql id="someSQL">id,name</sql>
</mapper>
CustomMapper.xml
<mapper namespace="com.company.CustomMapper"> <select id="selectSome" >select<include refid="com.company.ShareMapper.someSQL"/>from t</select>
</mapper>
注意事项:
最好基于单表来定义SQL片段
不要在sql片段中存在where标签
动态sql小结:
- 先在Mysql中写出完整的SQL,再对应的去修改成我们的动态SQL实现通用即可
- 动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
- 通过我们的入参的变化形成了动态的效果,如map.put 和 list.add
- 实际工作中的sql会非常多,会联很多的表
13、缓存
13.1 简介
查询 : 连接数据库,耗资源
一次查询的结果,给他暂存一个可以直接取到的地方 --> 内存:缓存
我们再次查询的相同数据的时候,直接走缓存,不走数据库了
13.2 MyBatis缓存 (目前Redis使用最多)
- MyBatis包含一个非常强大的查询缓存特性,它可以非常方便的定制和配置缓存,缓存可以极大的提高查询效率。
- MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,一级缓存开启(SqlSession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。 举例:namespace="com.yff.dao.BlogMapper" namespace级别即接口级别
- 为了提高可扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来定义二级缓存。
13.3 一级缓存
- 一级缓存也叫本地缓存:SqlSession
- 与数据库同一次会话期间查询到的数据会放在本地缓存中
- 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库
- 默认情况下,只有一级缓存开启(SqlSession级别的缓存,也称为本地缓存),只在SqlSession中有效,也无法关闭一级缓存,也就是拿到连接到关闭连接这个区间,一级缓存本质就是一个Map
测试步骤:
1.开启日志
2.测试在一个SqlSession中查询两次相同记录
@Testpublic void test1() {SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);User user = mapper.getUserById(1); -----System.out.println(user);System.out.println("=====================================");User user2 = mapper.getUserById(1); ------System.out.println(user2 == user);}
3.查看日志输出,数据库只查询了一次,第二次使用的缓存
一级缓存SqlSession失效的情况:
1.查询不同的东西(查询id=1和id=2)
2.增删改操作,可能会改变原来的数据,所以必定会刷新缓存,缓存会失效,会重新查询数据库
3.查询不同的Mapper.xml
二级缓存也会失效,更别提一级缓存了
4.手动清理缓存
sqlSession.clearCache();
13.4 二级缓存
1、二级缓存与一级缓存区别在于二级缓存的范围更大,多个sqlSession可以共享一个mapper中的二级缓存区域。
3、由于mybaits的二级缓存是mapper范围级别,所以除了在SqlMapConfig.xml设置二级缓存的总开关外,还要在具体的mapper.xml中开启二级缓存。
1.开启全局缓存(在mybatis核心配置文件里setting)
<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
<!--在当前Mapper.xml中使用二级缓存,这是复杂用法,设置了参数-->
<cacheeviction="FIFO"flushInterval="60000"size="512"readOnly="true"/><!--在当前Mapper.xml中使用二级缓存,这是简单用法,就使用默认的即可--> 一般就这样用
<cache/>
上述代码含义为:创建了一个 FIFO (io流的)缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的。
flushInterval:(刷新间隔)属性可以被设置为任意的正整数,设置的值应该是一个以毫秒为单位的合理时间量。 默认情况是不设置,也就是没有刷新间隔,缓存仅仅会在调用语句时刷新。
size:(引用数目)属性可以被设置为任意正整数,要注意欲缓存对象的大小和运行环境中可用的内存资源。默认值是 1024。
@Test
public void testCache2() throws Exception {SqlSession sqlSession1 = sqlSessionFactory.openSession();SqlSession sqlSession2 = sqlSessionFactory.openSession();SqlSession sqlSession3 = sqlSessionFactory.openSession();// 创建代理对象UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);// 第一次发起请求,查询id为1的用户User user1 = userMapper1.findUserById(1);System.out.println(user1); //这里执行关闭操作,将sqlsession中的数据写到二级缓存区域,重点-->执行关闭操作才会把将sqlsession中的数据写到二级缓存区域sqlSession1.close();//sqlSession3用来清空缓存的,如果要测试二级缓存,需要把该部分注释掉//使用sqlSession3执行commit()操作UserMapper userMapper3 = sqlSession3.getMapper(UserMapper.class);User user = userMapper3.findUserById(1);user.setUsername("倪升武");userMapper3.updateUser(user);//执行提交,清空UserMapper下边的二级缓存sqlSession3.commit();sqlSession3.close();UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);// 第二次发起请求,查询id为1的用户User user2 = userMapper2.findUserById(1);System.out.println(user2);sqlSession2.close();}
我们先把sqlSession3部分注释掉来测试一下二级缓存的结果:
当我们把sqlSession3部分加上后,再测试一下二级缓存结果:
其他配置(useCache和flushCache)
useCache:
<select id="findOrderListResultMap" resultMap="ordersUserMap" useCache="false">
<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User" flushCache="true">
13.5 缓存原理
13.6 自定义缓存-ehcache(用得少,Redis多)
Ehcache是一种广泛使用的开源Java分布式缓存框架。
<dependency><groupId>org.mybatis.caches</groupId><artifactId>mybatis-ehcache</artifactId><version>1.2.1</version>
</dependency>
2.在mapper中指定使用我们的 Ehcache 缓存实现类
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
13.7 cache-ref:引用缓存
<cache-ref namespace="com.someone.application.data.SomeMapper"/>
13.8 . MyBatis整合ehcache分布式缓存框架
所以我们为了解决这个问题,就得找一个分布式的缓存,专门用来存储缓存数据的,这样不同的服务器要缓存数据都往它那里存,取缓存数据也从它那里取,如下图所示:
导入了jar包后,配置mapper中cache中的type为ehcache对cache接口的实现类型。ehcache对cache接口有一个实现类为:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"><diskStore path="F:\develop\ehcache"/><defaultCachemaxElementsInMemory="10000"eternal="false"timeToIdleSeconds="120"timeToLiveSeconds="120"maxElementsOnDisk="10000000"diskExpiryThreadIntervalSeconds="120"memoryStoreEvictionPolicy="LRU"><persistence strategy="localTempSwap"/></defaultCache>
</ehcache>
编写ehcache.xml文件,如果在 加载时 未找到 /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>
最后,练习smbms的spring项目中的29道mybatis题
Mybatis_狂神(XML和注解,配置,lombok,动态sql,缓存等)相关推荐
- Java神鬼莫测之MyBatis注解开发之动态SQL语句(六)
1.Mybatis注解开发之动态SQL语句 背景:使用mybatis的注解开发动态Sql会比较麻烦, 很不方便, 所以不太推荐使用,该文章以查询作为案例,演示动态sql语句. 注意:Mybatis的动 ...
- 通用Mapper注解方式实现动态SQL
1.通用Mapper注解方式实现动态SQL 注意:使用动态SQL后,不能使用分页助手,需要手动写分页SQL 对应的mapper接口实现SelectMapper接口 在对应的mapper接口中的方法上
- JAVA日记之mybatis-3一对一,一对多,多对多xml与注解配置 ----喝最烈的酒.
1.Mybatis多表查询 1.1 一对一查询 1.1.1 一对一查询的模型 用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户 一对一查询的需求:查询一个订单,与此同时查询出该订单 ...
- Mybatis注解-注解方式的动态SQL语句
基于手写SQL语句的注解CRUD 把手写SQL语句的注解CRUD,修改为动态SQL语句方式. CategoryDynaSqlProvider 新增CategoryDynaSqlProvider,提供C ...
- Mybatis配置及动态SQL语句标签
#Mybatis resources: ###db.properties: jdbc.driver = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://lo ...
- 基于XML及注解配置方式实现AOP及aspectJ表达式
aspectJ表达式结构 切入点表达式 execution (* com.sample.service.impl...(..)) 1.execution(): 表达式主体. 2.第一个号:表示返回类型 ...
- MyBatis框架知识点大全,从0到1(配置文件和使用、手动和全自动映射、lombok使用、Mybatis测试工具类、动态SQL、通过注解来实现动态SQL和手动一对一、一对多、多对多映射)
MyBatis框架 这里写的感觉有点多,到时候拆开发,需要哪看目录就好
- spring IOC基本配置(xml配置和注解配置)
目录 Spring IOC IOC是什么 IOC可以做什么 依赖注入 IOC和DI IOC容器 Bean 配置IOC容器 spring ioc 依赖 XML配置 实例化容器 使用容器 xml配置详解 ...
- @Select注解动态sql语句
一.我们先看看xml配置的动态sql语句 二.如何使用注解也能达到这种效果呢? 1.先在sql里面加上标签<script> 2.之后就是用上面的配置,但是得注意双引号,和每一条语句的逗号分 ...
最新文章
- 棋盘上的孙子兵法之我见
- linux下添加用户并赋予root权限
- 上海人工智能实验室刘宇:从感知AI的发展理解决策AI的未来
- 爬虫必须得会的预备知识
- python的总结与心得词云设计理念_Python编程语言:使用词云来表示学习和工作报告的主题...
- 【分块】区间众数(金牌导航 分块-1)
- Java泛型中的多态
- 如何计算出int的数据范围
- 爬虫中 Selenium-Requets-模拟登陆cookie-代理proxy 的简单总结
- 怎样判断电饭锅温度传感器的好坏?_技术|怎样判断LED透明屏好坏
- 一个用户的上级部门的上级部门对用户也有修改权限,怎么判断?
- (Web前端)后台管理系统框架收集
- 微软服务器系统补丁kb2919355,Windows 8.1补丁KB2919355无法安装的解决方法
- 企业常见10个CRM问题答疑!
- 韩寒:给李彦宏先生的一封信
- 信息收集-CDN绕过
- Python爬虫实战 | (13) 爬取新浪滚动新闻
- 升腾 linux管理密码,升腾Linux终端使用指南
- 弘辽科技:淘宝新链接要怎么补流量?有没有提升新链接的办法?
- .计算机软件系统包括,计算机软件系统包括什么
热门文章
- 先进的管理技术将其转化成为有机的、高效的商业模式的管理集成
- FLV文件格式分析(附源码)
- IDEA连接SQL server之JDK版本问题
- Android存储设备(U盘,SD卡)状态监测(《Android 2.3 SD卡挂载流程浅析1234567)
- vue渲染缓慢我遇到的情况解决
- mysql 存储uuid_MySQL中存储UUID的最佳实践
- 新生美国生活常用单词汇总
- 第四章 分解方法及单口网络
- vue项目实战--如何在手机中查看vuecli3/vuecli2项目?
- 使用计算机求解雷达方程,关于雷达方程