mybatis入门实例

1、mybatis入门实例

maven依赖

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

导入依赖的时候注意!静态资源被忽略的问题!
要引入如下依赖,才能正常启动!

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

resource下配置
mybatis-config.xml 与 db.properties

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

    <properties resource="db.properties"/>
    <settings>
        <!--<setting name="logImpl" value="STDOUT_LOGGING"/>-->
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <plugins>
        <!-- com.github.pagehelper为PageHelper类所在包名 -->
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 使用MySQL方言的分页 -->
            <!--<property name="helperDialect" value="sqlserver"/>&lt;!&ndash;如果使用mysql,这里value为mysql&ndash;&gt;-->
            <property name="helperDialect" value="mysql"/><!--如果使用mysql,这里value为mysql-->
            <property name="pageSizeZero" value="true"/>
        </plugin>
    </plugins>
    <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 resource="org/mybatis/example/BlogMapper.xml"/>-->
        <!--<mapper resource="com/songyang/dao/UserMapper.xml"/>-->
        <mapper class="com.songyang.dao.UserMapper"/>
    </mappers>

</configuration>


注意!配置文件里面的顺序不能变,要严格按照官方文档中的顺序来写,否则会报错!

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

编写工具类

package com.songyang.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory = null;

    static {
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    public static SqlSession getConnection() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }


}

实体

public class User {
    private Integer id;
    private String name;
    private String pwd;

    private List<Car> list;
    //get set 省略
public class Car {
    private Long id;
    private String name;
    private Integer uid;
     //get set 省略

mapper接口 和xml文件

public interface UserMapper {
    List<User> getUsers();

    User getUserById(int id);

    User getInfo(@Param("name") String a, @Param("pwd") String b);

    User getByMap(Map<String, Object> map);

    int add(User user);

    int update(User user);

    boolean delete(@Param("id") Integer i);

    List<User> getLike(@Param("name") String aa);

    //分页查询
    List<User> queryUser();

    //一对多查询
    List<User> getL();
}

<?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.songyang.dao.UserMapper">
    <select id="getUsers" resultType="com.songyang.entity.User">
      select * from USER
    </select>

    <select id="getUserById" resultType="com.songyang.entity.User">
        select * from user where id =#{id}
    </select>

    <select id="getInfo" resultType="com.songyang.entity.User">
        select * from user where name= #{name} and pwd = #{pwd}
    </select>
    <select id="getByMap" parameterType="map" resultType="com.songyang.entity.User">
        select * from user where name= #{name} and pwd = #{pwd}
    </select>
    <insert id="add" parameterType="com.songyang.entity.User">
        insert  into  user(id,name,pwd) values(#{id},#{name},#{pwd})
    </insert>
    <update id="update" parameterType="com.songyang.entity.User">
        update user set name=#{name} where id = #{id}
    </update>
    <delete id="delete" parameterType="int">
        delete from user where  id= #{id}
    </delete>
    <select id="getLike" parameterType="String" resultType="com.songyang.entity.User">
        select  * from user  where name like "%"#{name}"%"
    </select>

    <select id="queryUser" resultType="com.songyang.entity.User">
        select  * from user
    </select>

    <!--一对多查询-->
    <select id="getL" resultMap="tt">
        SELECT a.id uid,a.`name` uname,b.id bid,b.`name` bname from user a  LEFT JOIN car b on a.id = b.uid;
    </select>
    <resultMap id="tt" type="com.songyang.entity.User">
        <id column="uid" property="id"/>
        <result column="uname" property="name"/>
        <collection property="list" ofType="com.songyang.entity.Car">
            <id column="bid" property="id"/>
            <result column="bname" property="name"/>
        </collection>
    </resultMap>
</mapper>

注意要在 Mybatis-config.xml 中注册!mapper接口和xml文件最好同名,才能用class引入

测试代码

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.songyang.dao.UserMapper;
import com.songyang.entity.User;
import com.songyang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.List;

public class Test {
    //    static Logger logger = Logger.getLogger(UserDaoTest.class);
    static Logger logger = Logger.getLogger(Test.class);
    //普通查询
    @org.junit.Test
    public void T1() {
        SqlSession connection = MybatisUtils.getConnection();
        UserMapper mapper = connection.getMapper(UserMapper.class);
        List<User> users = mapper.getUsers();
        System.out.println(users);
        connection.close();
    }
    //by id
    @org.junit.Test
    public void getById() {
        SqlSession connection = MybatisUtils.getConnection();
        UserMapper mapper = connection.getMapper(UserMapper.class);
        User userByid = mapper.getUserById(1);
        System.out.println(userByid);
        connection.close();
    }
    //全量查询
    @org.junit.Test
    public void getInfo() {
        SqlSession connection = MybatisUtils.getConnection();
        UserMapper mapper = connection.getMapper(UserMapper.class);
        User a = mapper.getInfo("张三", "111");
        System.out.println(a);
        connection.close();
    }
    //map封装查询接口
    @org.junit.Test
    public void getByMap() {
        SqlSession connection = MybatisUtils.getConnection();
        UserMapper mapper = connection.getMapper(UserMapper.class);
        HashMap<String, Object> map = new HashMap();
        map.put("name", "张三");
        map.put("pwd", "111");
        User a = mapper.getByMap(map);
        System.out.println(a);
        connection.close();
    }
    //添加
    @org.junit.Test
    public void add() {
        SqlSession connection = MybatisUtils.getConnection();
        UserMapper mapper = connection.getMapper(UserMapper.class);
        User h = new User(4, "欢", "444");
        int add = mapper.add(h);
        System.out.println(add);
        //提交事务
        connection.commit();
        connection.close();
    }
    //修改
    @org.junit.Test
    public void udpate() {
        SqlSession aa = MybatisUtils.getConnection();
        UserMapper mapper = aa.getMapper(UserMapper.class);
        User liu = new User(4, "刘欢", "444");
        int update = mapper.update(liu);
        System.out.println(update);
        aa.commit();
        aa.close();
    }
    //删除  返回BOOlean
    @org.junit.Test
    public void del() {
        SqlSession connection = MybatisUtils.getConnection();
        UserMapper mapper = connection.getMapper(UserMapper.class);
        boolean delete = mapper.delete(4);
        System.out.println(delete);
        connection.commit();
        connection.close();
    }
    //模糊查询
    @org.junit.Test
    public void getLike() {
        logger.info("=============like===============");
        SqlSession connection = MybatisUtils.getConnection();
        UserMapper mapper = connection.getMapper(UserMapper.class);
        List<User> like = mapper.getLike("李");
        System.out.println(like);
        connection.close();
    }
    //分页查询
    @org.junit.Test
    public void fenye() {
        SqlSession connection = MybatisUtils.getConnection();
        UserMapper mapper = connection.getMapper(UserMapper.class);
        PageHelper.startPage(1, 2, true);
        List<User> users = mapper.queryUser();
//        System.out.println(users);
        PageInfo<User> userPageInfo = new PageInfo<User>(users);
        System.out.println(userPageInfo);
        connection.close();
    }
    //一对多
    @org.junit.Test
    public void many(){
        SqlSession connection = MybatisUtils.getConnection();
        UserMapper mapper = connection.getMapper(UserMapper.class);
        List<User> l = mapper.getL();
        System.out.println(l);
    }
}

注意一对多的相关字段
property中填写集合在User这个bean中的属性名称,此时是list
ofType中填写集合的泛型 此时是 Car

log4j.properties 日志配置
必须取这个名字mybatis才能识别,用slf日志也要取这个名字

### set log levels ###
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/hou.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

2、分页查询

maven依赖

        <!--分页-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.6</version>
        </dependency>

mybatis-config.xml中配置

    <plugins>
        <!-- com.github.pagehelper为PageHelper类所在包名 -->
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 使用MySQL方言的分页 -->
            <!--<property name="helperDialect" value="sqlserver"/>&lt;!&ndash;如果使用mysql,这里value为mysql&ndash;&gt;-->
            <property name="helperDialect" value="mysql"/><!--如果使用mysql,这里value为mysql-->
            <property name="pageSizeZero" value="true"/>
        </plugin>
    </plugins>

接口 与 xml

    //分页查询
    List<User> queryUser();
    
    <select id="queryUser" resultType="com.songyang.entity.User">
        select  * from user
    </select>

用法:

    //分页查询
    @org.junit.Test
    public void fenye() {
        SqlSession connection = MybatisUtils.getConnection();
        UserMapper mapper = connection.getMapper(UserMapper.class);
        PageHelper.startPage(1, 2, true);
        List<User> users = mapper.queryUser();
//        System.out.println(users);
        PageInfo<User> userPageInfo = new PageInfo<User>(users);
        System.out.println(userPageInfo);
        connection.close();
    }

3、一对多查询

    <!--一对多查询-->
    <select id="getL" resultMap="tt">
        SELECT a.id uid,a.`name` uname,b.id bid,b.`name` bname from user a  LEFT JOIN car b on a.id = b.uid;
    </select>
    <resultMap id="tt" type="com.songyang.entity.User">
        <id column="uid" property="id"/>
        <result column="uname" property="name"/>
        <collection property="list" ofType="com.songyang.entity.Car">
            <id column="bid" property="id"/>
            <result column="bname" property="name"/>
        </collection>
    </resultMap>

4、动态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 namespace="com.ly.bems.service.fee.mapper.AccDetailMapper">

    <sql id="where">
        <if test="pars.id!=null">
            AND id = #{pars.id}
        </if>
        <if test="pars.buildingId!=null">
            AND building_id = #{pars.buildingId}
        </if>
        <if test="pars.info!=null and pars.info!=''">
            AND member_name1 LIKE CONCAT('%',#{pars.info},'%')
        </if>
        <if test="pars.startTime != null">
            <![CDATA[
            AND create_time >= #{pars.startTime}
            ]]>
        </if>
        <if test="pars.ids!=null and pars.ids.size()>0">
            AND id in
            <foreach collection="pars.ids" item="id" open="(" separator="," close=")">
                #{id}
            </foreach>
        </if>
    </sql>

    <insert id="addAccDetail">
        INSERT INTO acc_detail (
        <trim suffix="" suffixOverrides=",">
            <if test="id!=null">
                id,
            </if>
            <if test="buildingId!=null">
                building_id,
            </if>
            <if test="memberId1!=null">
                member_id1,
            </if>
        </trim>
        )
        VALUES (
        <trim suffix="" suffixOverrides=",">
            <if test="id!=null">
                #{id},
            </if>
            <if test="buildingId!=null">
                #{buildingId},
            </if>
            <if test="memberId1!=null">
                #{memberId1},
            </if>
        </trim>
        )
    </insert>

    <update id="updateAccDetail">
        UPDATE acc_detail SET
        <trim suffixOverrides="," suffix="">
            <if test="cols.buildingId!=null">
                building_id = #{cols.buildingId},
            </if>
            <if test="cols.memberId1!=null">
                member_id1 = #{cols.memberId1},
            </if>
            <if test="cols.memberId2!=null">
                member_id2 = #{cols.memberId2},
            </if>
        </trim>
        WHERE
        <trim prefixOverrides="AND|OR" prefix="">
            <include refid="where"/>
        </trim>
    </update>

    <select id="queryAccDetail" resultType="AccDetailResult">
        SELECT
        <trim suffix="" suffixOverrides=",">
            <if test="cols.id!=null">
                id id,
            </if>
            <if test="cols.buildingId!=null">
                building_id buildingId,
            </if>
            <if test="cols.memberId1!=null">
                member_id1 memberId1,
            </if>
        </trim>
        FROM acc_detail
        <where>
            <include refid="where"/>
        </where>
        <if test="pars.orderBy!=null and pars.orderBy!=''">
            ORDER BY ${pars.orderBy}
        </if>
    </select>

    <delete id="deleteAccDetail">
        DELETE FROM acc_detail
        WHERE
        <trim prefixOverrides="AND|OR" prefix="">
            <include refid="where"/>
        </trim>
    </delete>
</mapper>

5、缓存

  • myBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
  • MyBatis系统中默认定义了两级缓存:一级缓存二级缓存
  • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
  • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
  • 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
    一级缓存
    一级缓存也叫本地缓存:
    与数据库同一次会话期间查询到的数据会放在本地缓存中。
    以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;

一级缓存失效的四种情况

  • 一级缓存是SqlSession级别的缓存,是一直开启的,我们关闭不了它;
  • 一级缓存失效情况:没有使用到当前的一级缓存,效果就是,还需要再向数据库中发起一次查询请求!

1、sqlSession不同

@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   SqlSession session2 = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);
   UserMapper mapper2 = session2.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);
   User user2 = mapper2.queryUserById(1);
   System.out.println(user2);
   System.out.println(user==user2);

   session.close();
   session2.close();
}

观察结果:发现发送了两条SQL语句!

结论:每个sqlSession中的缓存相互独立

2、sqlSession相同,查询条件不同

@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);
   UserMapper mapper2 = session.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);
   User user2 = mapper2.queryUserById(2);
   System.out.println(user2);
   System.out.println(user==user2);

   session.close();
}

观察结果:发现发送了两条SQL语句!很正常的理解

结论:当前缓存中,不存在这个数据

3、sqlSession相同,两次查询之间执行了增删改操作!

增加方法

//修改用户

int updateUser(Map map);
编写SQL

<update id="updateUser" parameterType="map">
  update user set name = #{name} where id = #{id}
</update>
测试

@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);

   HashMap map = new HashMap();
   map.put("name","kuangshen");
   map.put("id",4);
   mapper.updateUser(map);

   User user2 = mapper.queryUserById(1);
   System.out.println(user2);

   System.out.println(user==user2);

   session.close();
}

观察结果:查询在中间执行了增删改操作后,重新执行了

结论:因为增删改操作可能会对当前数据产生影响

4、sqlSession相同,手动清除一级缓存

@Test
public void testQueryUserById(){
   SqlSession session = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);

   User user = mapper.queryUserById(1);
   System.out.println(user);

   session.clearCache();//手动清除缓存

   User user2 = mapper.queryUserById(1);
   System.out.println(user2);

   System.out.println(user==user2);

   session.close();
}

一级缓存就是一个map

二级缓存

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

工作机制

  • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
  • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
    新的会话查询信息,就可以从二级缓存中获取内容;
  • 不同的mapper查出的数据会放在自己对应的缓存(map)中;
    使用步骤
    1、开启全局缓存 【mybatis-config.xml】
<setting name="cacheEnabled" value="true"/>

2、去每个mapper.xml中配置使用二级缓存,这个配置非常简单;【xxxMapper.xml】

官方示例=====>查看官方文档

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

所有的实体类先实现序列化接口
测试代码
@Test
public void testQueryUserById(){
SqlSession session = MybatisUtils.getSession();
SqlSession session2 = MybatisUtils.getSession();

UserMapper mapper = session.getMapper(UserMapper.class);
UserMapper mapper2 = session2.getMapper(UserMapper.class);

User user = mapper.queryUserById(1);
System.out.println(user);
session.close();

User user2 = mapper2.queryUserById(1);
System.out.println(user2);
System.out.println(user==user2);

session2.close();
}
结论

  • 只要开启了二级缓存,我们在同一个Mapper中的查询,可以在二级缓存中拿到数据
  • 查出的数据都会被默认先放在一级缓存中
  • 只有会话提交或者关闭以后,一级缓存中的数据才会转到二级缓存中

第三方缓存实现–EhCache: 查看百度百科

  • Ehcache是一种广泛使用的java分布式缓存,用于通用缓存;

  • 要在应用程序中使用Ehcache,需要引入依赖的jar包

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

在mapper.xml中使用对应的缓存即可

<mapper namespace = “org.acme.FooMapper” >
   <cache type = “org.mybatis.caches.ehcache.EhcacheCache” />
</mapper>

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

合理的使用缓存,可以让我们程序的性能大大提升!

6、注解的一些说明

  • @Param注解用于给方法参数起一个名字。以下是总结的使用原则:
  • 在方法只接受一个参数的情况下,可以不使用@Param。
  • 在方法接受多个参数的情况下,建议一定要使用@Param注解给参数命名。
  • 如果参数是 JavaBean , 则不能使用@Param。
  • 不使用@Param注解时,参数只能有一个,并且是Javabean。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值