【推荐】springboot mybatis ehcache 的demo

实验目的,测试ehcache

关键出错误的地方,

1,数据库驱动,url地址写错,最后界别是?,不是斜杠,否则报告字符串too long的错误。druid的默认连接池初始化为1,即可。

2,入口启动类要加入@MapperScan(basePackages = {"cn.taotao.dao"}),

3,在yml配置文件中,指定mapper的local位置,否则报告Invalid bound statement (not found):,参数绑定错误。

4,在进行test时,把已经生成generator的test,注释掉,否则会重复生成。

5,在ehcache的配置中,其中在yml中启用cache并不管用,还需要在mapper中,引入ehcache,<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache> ,然后在资源根目录,建立ehcache.xml文件,与appllicaton.yml 同级,文件名称默认就是ehcache.xml

 另参考

springboot 集成 mybatis

druid的springboot(不推荐)

 


 

搭建环境

pom,

引入druid的包,mysql数据驱动,mybatis的ehcache,mybatis的starter,

<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.4.0</version>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.4</version>
</dependency>

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.caches</groupId>
            <artifactId>mybatis-ehcache</artifactId>
          <version>1.1.0</version> 
        </dependency>

 

第二步

编写yml文件

server:
  port: 80
spring:
  mvc:
    view:
      suffix: .jsp
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
      username: root
      password: xxxxx
      initial-size: 1
      min-idle: 1
      max-active: 50
      max-wait: 15000
      #监控配置
      stat-view-servlet:
        allow: 
        deny: 
        url-pattern: /druid/*
        enabled: true
        login-username: system
        login-password: 123456
      
mybatis:
  mapper-locations:
  - classpath:mapper/*Mapper.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  
    
    
  

一定注意,在mybatis上,写入mapper-location的包的路径,否则测试时报告参数异常

invalid bound,之类的错误

第三步编写实体类

用mybatis generator生产,生成后,一定要把@test,注释掉,否则会重复生成。

//@Test
    public void MybatisGenerator()  {
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true;
            File configFile = new File("MybatisGenerator.xml");
            ConfigurationParser cp = new ConfigurationParser(warnings);
            try {
                Configuration config = cp.parseConfiguration(configFile);
                DefaultShellCallback callback = new DefaultShellCallback(overwrite);
                MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
                myBatisGenerator.generate(null);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            
            }
        }
    

 MyGenerator.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>

    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!-- 配置数据库连接 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/test" userId="root"
            password="xxxxxxx">
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- 指定javaBean生成的位置 -->
        <javaModelGenerator targetPackage="cn.taotao.bean"
            targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!--指定sql映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="mapper"
            targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!-- 指定dao接口生成的位置,mapper接口 -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="cn.taotao.dao" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>


        <!-- table指定每个表的生成策略 -->
        <table tableName="tbl_user" domainObjectName="User"
            enableCountByExample="false" enableDeleteByExample="false"
            enableUpdateByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false"></table>
        <table tableName="tbl_dept" domainObjectName="Dept"
            enableCountByExample="false" enableDeleteByExample="false"
            enableUpdateByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false"
        >
        <columnOverride column="deptinfo" javaType="java.lang.String" jdbcType="VARCHAR"></columnOverride>   <!--text类型的,转为varchar类型-->
        </table>
    </context>
</generatorConfiguration>

其中targetProject 可以写成 全路径名称,如c:\project\xxx\

第四步,编写其他

在启动入口类上加入

@MapperScan(basePackages = "cn.taotao.dao")

否则回报没有合适的bean注入,提升要提供至少一个符合条件的bean。

第五步,编写ehcache的配置文件,其中内存数量建议小一点,否则可能会造成jvm的内存溢出。

<?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">
<!-- xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" -->
    <!-- 磁盘保存路径 -->
    <diskStore path="D:\44test\ehcache" />

    <defaultCache maxElementsInMemory="1000"
        maxElementsOnDisk="10000000" eternal="false" overflowToDisk="true"
        timeToIdleSeconds="120" timeToLiveSeconds="120"
        diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU">
    </defaultCache>
     
    
    
</ehcache>

<!-- 属性说明: l diskStore:指定数据在磁盘中的存储位置。 l defaultCache:当借助CacheManager.add("demoCache")创建Cache时,EhCache便会采用<defalutCache/>指定的的管理策略 
    以下属性是必须的: l maxElementsInMemory - 在内存中缓存的element的最大数目 l maxElementsOnDisk 
    - 在磁盘上缓存的element的最大数目,若是0表示无穷大 l eternal - 设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断 
    l overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上 以下属性是可选的: l timeToIdleSeconds 
    - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时,这些数据便会删除,默认值是0,也就是可闲置时间无穷大 
    l timeToLiveSeconds - 缓存element的有效生命期,默认是0.,也就是element存活时间无穷大 diskSpoolBufferSizeMB 
    这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区. l diskPersistent 
    - 在VM重启的时候是否启用磁盘保存EhCache中的数据,默认是false。 l diskExpiryThreadIntervalSeconds 
    - 磁盘缓存的清理线程运行间隔,默认是120秒。每个120s,相应的线程会进行一次EhCache中数据的清理工作 l memoryStoreEvictionPolicy 
    - 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出) -->

第六步编写测试

//@Test
    public void insertUser() {
        for (int i = 0; i < 1000; i++) {
            userService.insertSelective(new User("xiaoming"+i,"beijing"+i,i%5,new Date()));
        }
        
    }
    
    @Test
    public void testSelect() {
        for (int i = 0; i <1000; i++) {
            System.out.println(this.userService.selectByPrimaryKey((new Random()).nextInt(2000)));
        }
    }

 

posted @ 2021-03-16 15:29  琴声清幽  阅读(89)  评论(0编辑  收藏  举报