MyBatis
MyBatis
创建过程
-
在mysql中创建一个数据库
-
搭建java运行环境
- Maven搭建
- 在pom.xml中导入依赖
<!-- 导入依赖--> <dependencies> <!--mysgl驱对--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version><!--根据自己需要版本导入--> </dependency> <!--mybatis--> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactid> <version>4.12</version> </dependency> </dependencies> <!--在build中配置resources,来防止我们资源导出失败的问题--> <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>
-
创建项目模块
-
在resources目录下搭建MyBatis配置文件,命名为mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration "PUBLIC"-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!--configuration 核心配置文件,链接数据库--> <configuration> <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&useUnicode=true&characterEncoding=UTF-8"/> <propertyname="username" value="自己的用户名"/> <propertyname="password" value="自己的密码"/> </dataSource> </environment> </environments> <!--每一个Mapper.XML 都需要在Mybatis 核心既置文件中注册! --> <mappers> <mapper resource="自己的Mapper.xml地址,中间用“/”隔开"/> </mappers> </configuration>
-
搭建MyBatis工具类(在java目录下建立utils)
//sglSessionFactory --> sglSession public class MybatisUtils{ private static SqlSessionFactory sqlSessionFactory; static{ try{ //使用Mybatis第一步: 获取slSessionFactory对象 String resource ="mybatis-config.xml";//对应MyBatis配置文件 InputStream inputStream =Resources.getResourceAsStream(resource); sglSessionFactory = new SalSessionFactoryBuilder().build(inputStream); }catch (IOException e) { e.printStackTrace(); } } //既然有了 SqLSessionFactory,顾名思义,我们就可以从中获得 SqLSession 的实例了。 // SgLSession 完全包含了面向数据库执行 SOL 命所需的所有方法。 public static SqlSession getqlSession(){ return sglSessionFactory.openSession(); } }
-
建立pojo目录,创建实体类
- 表单名
- 无参构造
- 有参构造
- set函数
- get函数
-
建立Mapper目录,建立Mapper接口和Mapper.xml,进行数据库操作
Mapper接口:
public interface UserMapper { List<User> getUserList(); //根ID查询用户 User getUserById(int id); //insert增加一个用户 int addUser(User user); //修改用户 int updateUser(User user); //删除一个用户 int deleteUser(int id); }
Mapper.xml:
<?xml version="1." 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="自己的Mapper接口地址"> <!--select查询语句,resultType返回单个值,resultMap进行结果集映射--> <select id="getUserList(对应Mapper接口中的方法)" resultType="自己实体类的地址"> select * from mybatis.user<!--填写sql语句--> </select> <!--#{}锁定实体类中对应数据库的值--> <select id="getUserById" parameterType="int"resultType="自己实体类的地址"> select * from mybatis.user where id = #{id} </select> <!--对象中的属性,可以直接取出来--> <!--增加--> <insert id="addUser" parameterType="自己实体类的地址"> insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd}) </insert> <!--修改--> <update id="updateUser" parameterType="自己实体类的地址"> update mybatis.user set name=#{name},pwd=#{pwd} where id = #{id} ; </update> <!--删除--> <delete id="deleteUser"parameterType="int"> delete from mybatis .user where id = #{id}; </delete> </mapper>
-
测试
public class UserDaoTest { @Test public void test(){ //第一步:获得SgLsession对象 SqlSession sqlSession = MybatisUtils.getSglSession(); // getMapper getMapperUserDao userDao = sqlSession.getMapper(UserDao.class);//值为接口的类 List<User> userList = userDao.getUserList(); for(User user : userList) { System.out.println(user); } //关闭sqLsession sqlSession.close(); } }
CRUD(增删改查)
增删改需要提交事务
- id:就是对应的namespace中的方法名
- resultType: Sql语句执行的返回值!
- parameterType:参数类型!
<mapper namespace="自己的Mapper接口地址">
<!--查询-->
<!--#{}锁定实体类中对应数据库的值-->
<select id="getUserById" parameterType="int" resultType="自己实体类的地址">
select * from mybatis.user where id = #{id}
</select>
<!--增加-->
<!--对象中的属性,可以直接取出来-->
<insert id="addUser" parameterType="自己实体类的地址">
insert into mybatis.user (id, name, pwd) values (#{id),#{name},#{pwd});
</insert>
<!--修改-->
<!--对象中的属性,可以直接取出来-->
<update id="updateUser" parameterType="自己实体类的地址">
update mybatis.user set name=#{name},pwd=#{pwd} where id = #{id} ;
</update>
<!--删除-->
<delete id="deleteUser"parameterType="int">
delete from mybatis .user where id = #{id};
</delete>
</mapper>
Map
Mapper接口:
public interface UserMapper {
List<User> getUserList();
//根ID查询用户
User getUserById(Map<String,Object> map);
}
Mapper.xml:
<?xml version="1." 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="自己的Mapper接口地址">
<!--select查询语句,resultType返回单个值,resultMap返回多个值-->
<select id="getUserById" resultType="map">
select * from mybatis.user where id = #{Byid}
</select>
</mapper>
测试:
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSglSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String, object>();
//put函数中对应的键应与Mapper.xml中#{}设置的值对应
map.put("Byid",5);
mapper.adduser2(map);
sqlSession.close();
}
配置
xml中可以规定每个标签的放置顺序
mybatis-config.xml的configuration标签的顺序为properties、setting、typeAliases
属性改良(properties)
db.properties:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username = 自己的用户名
pwd = 自己的密码
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>
<!-- 引入外部配置文,在resources目录下建立db.properties-->
<properties resource="db.properties">
<!--可添加属性,功能相当于db.properties
<property name="username" value="root"/>
<property name="pwd" value="11111"/>
</property>-->
</properties>
<environments default="development">
<environment id="development"
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value=${driver}/>
<property name="url"value=${url}/>
<propertyname="username" value=${username}/>
<propertyname="password" value=${pwd}/>
</dataSource>
</environment>
</environments>
<!--每一个Mapper.XML 都需要在Mybatis 核心既置文件中注册! -->
<mappers>
<mapper resource="自己的Mapper.xml地址,中间用“/”隔开"/>
</mappers>
</configuration>
别名(typeAliases)
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>
<!-- 引入外部配置文,在resources目录下建立db.properties-->
<properties resource="db.properties"/>
<!-- 可以给实体类起别名 alias="别名"-->
<typeAliases>
<typeAlias type="实体类地址"alias="User"/>
<!--package导入后引入别名为实体类名字对应小写字母,如:实体类为User,则别名为user-->
<!--如果需要自定义别名,需要在实体类上增加注解@Alias("别名") -->
<package name="实体类对应包的地址"/>
</typeAliases>
<environments default="development">
<environment id="development"
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value=${driver}/>
<property name="url"value=${url}/>
<propertyname="username" value=${username}/>
<propertyname="password" value=${pwd}/>
</dataSource>
</environment>
</environments>
<!--每一个Mapper.XML 都需要在Mybatis 核心既置文件中注册! -->
<mappers>
<mapper resource="自己的Mapper.xml地址,中间用“/”隔开"/>
</mappers>
</configuration>
Mapper.xml:
<?xml version="1." 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="自己的Mapper接口地址">
<select id="getUserList" resultType="User<!--对应typeAliases中取的别名-->">
select * from mybatis.user
</select>
</mapper>
设置(Setting)
日志工厂
在mybatis-config.xml中配置:
<settings>
<!--标准日志工厂实现-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
LOG4j
- 导入Maven包
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
- 设置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/logFile.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
- 在mybatis-config.xml中配置log4j为日志的实现
<settings>
<!--日志工厂2-->
<setting name="logImpl" value="LOG4j"/>
</settings>
- 一般使用
- 导包 org.apache.log4j.Logger
- 导入静态对象static Logger Logger = Logger.getLogger(UserDaoTest.class);
public class UserDaoTest {
static Logger Logger = Logger.getLogger(UserDaoTest.class);
@Test
public void testLog4j(){
Logger.info("info:进入了testLog4j");
logger.debug("debug:进入 ItestLog4j");
logger.error("error:进入了testLog4j");
}
}
映射器(mappers)
方式一:
<mappers>
<mapper resource="com/zzy/dao/userMapper.xm1"/>
</mappers>
方式二:使用class文件绑定注册
<!--每一个Mapper.XML都需要在Mybatis核心配置文件中注册! -->
<mappers>
<mapper class="com. kuang.dao.userMapper"/>
</mappers>
注意点:
- 接口和他的Mapper配置文件必须同名!
- 接口和他的Mapper配置文件必须在同一个包下!
方式三:使用扫描包进行注入绑定
<!--每一个Mapper.XML都需要在Mybatis核心配置文件中注册! -->
<mappers>
<package name="com.zzy.dao"/>
</mappers>
注意点:
- 接口和他的Mapper配置文件必须同名!
- 接口和他的Mapper配置文件必须在同一个包下!
MyBatis注解
- 查
- 在接口处使用@select("sql语句")
- 增
- 在接口处使用@Insert("sql语句")
- 删
- 在接口处使用@Delete("sql语句")
- 改
- 在接口处使用@Update("sql语句")
注意:我们必须要讲接口注册绑定到我们的核心配置文件中!
public interface UserMapper {
@Select("select * from mybatis.user")
List<User> getUserList();
@Select("select * from mybatis.user where id = #{id}")
//有多个参数时加上@Param设置参数
User getUserById(@Param("id") int id);
//#{}一般与实体类对应,除非使用@Param(" ")更改
@Insert("insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd});")
int addUser(User user);
@Update("update mybatis.user set name=#{name},pwd=#{pwd} where id = #{id};")
int updateUser(User user);
@Delete("delete from mybatis .user where id = #{id};")
int deleteUser(int id);
}
-
我们可以在工具类创建的时候实现自动提交事务!(不推荐)
-
pub1ic static sqlsession getsqlsession(){ return sqIsessionFactory.openSession(true); }
-
Lombok
安装jar包
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.1</version>
</dependency>
</dependencies>
包含的注解
@Getter and @setter
@Fie1dNameConstants
@Tostring
@Equa1sAndHashCode
@A11ArgsConstructor,@RequiredArgsConstructor and @NoArgsConstructor
@Log,@Log4j,@Log4j2,@s1f4j,@xs1f4j,@commonsLog,@JBossLog, @Flogger
@Data
@Bui1der
@singular
@peTegate
@vaTue
@Accessors
@wither
@sneakyThrows
说明:
@Data: 无参构造,get、set、tostring、hashcode,equals
@A11ArgsConstructor 有参
@NoArgsConstructor 无参
@Equa1sAndHashCode
@Tostring
多对一
环境搭建
- 建立实体类,子实体类中需有父实体类中的对象
如:
public class Teacher{
private int id;
private String name;
}
public class Student{
private int id;
private String name;
private int tid;
//在Student中键入Teacher的对象
private Teacher teacher;
}
- 建立一个Mapper.xml(一个实体类建立一个xml)
<?xml version="1." 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="自己的Mapper接口地址">
</mapper>
- 在mybatis-config.xml中关联Mapper.xml
实现多对一
- 法一:按照查询进行嵌套处理
<?xml version="1." 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="自己的Mapper接口地址">
<select id="getStudent" resultMap="studentTeacher">
select * from student
</select>
<!--进行结果集映射resultMap的id关联所需select的resultMap-->
<resultMap id="studentTeacher" type="student">
<!--Student的id与数据库中id参数关联-->
<result property="id" column="id"/>
<!--Student的name与数据库中name参数关联-->
<result property="name" column="name"/>
<!--复杂的属性,我们需要单独处理 对象: association 集合: collection -->
<!--
Student与Teacher关联,
Student类中的teacher与数据库中tid关联(property,column)
Student类与Teacher类关联(javaType)
与Teacher接口中的方法getTeacher关联
-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{tid}
</select>
</mapper>
- 法二:按照结果嵌套处理-
<?xml version="1." 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="自己的Mapper接口地址">
<select id="getStudent2" resultMap="studentTeacher2">
select s.id sid,s .name sname,t.name tname
from student s,teacher t
where s.tid = t.id;
</select>
<resultMap id="studentTeacher2" type="student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher"javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
</mapper>
一对多
环境搭建
- 建立实体类,父实体类中需有子实体类中的对象
如:
public class Teacher{
private int id;
private String name;
//在Teacher中键入Student的对象
private List<Student> syudent;
}
public class Student{
private int id;
private String name;
}
- 建立一个Mapper.xml(一个实体类建立一个xml)
<?xml version="1." 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="自己的Mapper接口地址">
</mapper>
- 在mybatis-config.xml中关联Mapper.xml
实现一对多
- 法一:按结果嵌套查询
<?xml version="1." 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="自己的Mapper接口地址">
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid, s.name sname, t.name tname,t.id tid
from student s,teacher t
where s.tid = t.id and t.id = #{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!-- 复杂的属性,我们需要单独处理对象: association 集合:collection
javaType="” 指定属性的类型!
集合中的泛型信息,我们使用ofType 获取-->
<collection property="students" ofType="Student">
<resultproperty="id" column="sid"/>
<resultproperty="name" column="sname"/>
<result property="tid"column="tid"/>
</collection>
</resultMap>
</mapper>
- 法二:按照查询进行嵌套处理
<?xml version="1." 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="自己的Mapper接口地址">
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from mybatis .teacher where id = #{tid}
</select>
<resultMap id="Teacherstudent2" type="Teacher">
<collection property="students" column="id" javaType="ArrayList" ofType="student".select="getStudentByTeacherId"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="student">
select * from mybatis.student where tid = #{tid}
</select>
</mapper>
动态SQl
环境搭建
- 导包
- 编写配置文件
- 编写实体类
- 编写实体类对应Mapper接口和 Mapper.XML文件
if
<?xml version="1." 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="自己的Mapper接口地址">
<select id="getTeacher2" resultType="自己实体类的地址">
select * from mybatis .teacher where id = #{tid}
<if test="条件">
and title = #{title} <!--拼接的sql语句-->
</if>
</select>
</mapper>
where(解决where与and的拼接问题)
<?xml version="1." 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="自己的Mapper接口地址">
<select id="getTeacher2" resultType="自己实体类的地址">
select * from mybatis .teacher
<where>
<if test="条件">
and title = #{title} <!--拼接的sql语句-->
</if>
</where>
</select>
</mapper>
set(处理多个后缀需要 "," 的SQL语句)
<?xml version="1." 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="自己的Mapper接口地址">
<update id="getTeacher2" resultType="自己实体类的地址">
update * from mybatis .teacher
<set>
<if test="条件">
title = #{title}, <!--拼接的sql语句-->
</if>
where id = #{id}
</set>
</update>
</mapper>
choose;when(相当于java中的Switch)
<?xml version="1." 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="自己的Mapper接口地址">
<select id="getTeacher2" resultType="自己实体类的地址">
select * from mybatis .teacher
<choose>
<when test="条件">
and title = #{title} <!--拼接的sql语句-->
</when>
<when test="条件">
and title = #{title} <!--拼接的sql语句-->
</when>
</choose>
</select>
</mapper>
SQL片段
1.使用SQL标签抽取公共的部分
<sql id="if-title-author">
<if test="title != nu11">
title = #{title]
</if>
<if test="author != null">
and author = #{author}
</if>
</sq1>
2.在需要使用的地方使用Include标签引用即可
<select id="queryBlogIF" parameterType="map" resultType="blog">
seTect * from mybatis.blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
foreach(进行遍历集合时使用)
<select id="queryBlogForeach" parameterType="map"resultType="blog">
select * from mybatis.blog
<where>
<!--collection="集合名" item="查询名" open="查询前缀" close="查询后缀" separator="分隔符"-->
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
<!-- 此语句相当于
select * from mybatis.blog and ( x or x or x or ...)
-->
缓存
二级缓存
- 开启缓存
在mybatis-config.xml中设置
<!-- 显示的开启全局缓存-->
<setting name="cacheEnabled” value="true"/>
- 导入缓存
在Mapper.xml中设置
<!-- 在当前Mapper.xml中使用二级缓存-->
<cache/>
自定义缓存
- 导包
<dependency>
<groupld>org.mybatis.caches</groupld>
<artifactld>mybatis-ehcache</artifactld>
<eversion>1.1.0</version>
</dependency>
- 导入自定义缓存
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
- 配置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="java.io.tmpdir/Tmp_EhCache"/>
<!--
defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
-->
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<!--
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,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
-->
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现