当前位置 主页 > 服务器问题 > Linux/apache问题 >

    Mybatis如何通过注解开启使用二级缓存

    栏目:Linux/apache问题 时间:2019-11-10 10:48

    这篇文章主要介绍了Mybatis基于注解开启使用二级缓存,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    本文主要是补充一下Mybatis中基于注解的二级缓存的开启使用方法。

    1.在Mybatis的配置文件中开启二级缓存

    <?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>
      <settings>
        <!--开启全局的懒加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--<!–关闭立即加载,其实不用配置,默认为false–>-->
        <!--<setting name="aggressiveLazyLoading" value="false"/>-->
        <!--开启Mybatis的sql执行相关信息打印-->
        <setting name="logImpl" value="STDOUT_LOGGING" />
        <!--默认是开启的,为了加强记忆,还是手动加上这个配置-->
        <setting name="cacheEnabled" value="true"/>
      </settings>
      <typeAliases>
        <typeAlias type="com.example.domain.User" alias="user"/>
        <package name="com.example.domain"/>
      </typeAliases>
      <environments default="test">
        <environment >
          <!--配置事务-->
          <transactionManager type="jdbc"></transactionManager>
          <!--配置连接池-->
          <dataSource type="POOLED">
            <property name="driver" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/test1"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
          </dataSource>
        </environment>
      </environments>
      <mappers>
        <package name="com.example.dao"/>
      </mappers>
    </configuration>

    开启缓存 <setting name="cacheEnabled" value="true"/>,为了查看Mybatis中查询的日志,添加 <setting name="logImpl" value="STDOUT_LOGGING" />开启日志的配置。

    2.领域类以及Dao

    public class User implements Serializable{
      private Integer userId;
      private String userName;
      private Date userBirthday;
      private String userSex;
      private String userAddress;
      private List<Account> accounts;
      省略get和set方法...... 
    }
    
    import com.example.domain.User;
    import org.apache.ibatis.annotations.*;
    import org.apache.ibatis.mapping.FetchType;
    
    import java.util.List;
    @CacheNamespace(blocking = true)
    public interface UserDao {
      /**
       * 查找所有用户
       * @return
       */
      @Select("select * from User")
      @Results(id = "userMap",value = {@Result(id = true,column = "id",property = "userId"),
          @Result(column = "username",property = "userName"),
          @Result(column = "birthday",property = "userBirthday"),
          @Result(column = "sex",property = "userSex"),
          @Result(column = "address",property = "userAddress"),
          @Result(column = "id",property = "accounts",many = @Many(select = "com.example.dao.AccountDao.findAccountByUid",fetchType = FetchType.LAZY))
      })
      List<User> findAll();
    
      /**
       * 保存用户
       * @param user
       */
      @Insert("insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})")
      void saveUser(User user);
    
      /**
       * 更新用户
       * @param user
       */
      @Update("update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}")
      void updateUser(User user);
    
      /**
       * 删除用户
       * @param id
       */
      @Delete("delete from user where id=#{id}")
      void deleteUser(Integer id);
    
      /**
       * 查询用户根据ID
       * @param id
       * @return
       */
      @Select("select * from user where id=#{id}")
      @ResultMap(value = {"userMap"})
      User findById(Integer id);
    
      /**
       * 根据用户名称查询用户
       * @param name
       * @return
       */
    //  @Select("select * from user where username like #{name}")
      @Select("select * from user where username like '%${value}%'")
      List<User> findByUserName(String name);
    
      /**
       * 查询用户数量
       * @return
       */
      @Select("select count(*) from user")
      int findTotalUser();
    }