总结

文章目录

  • mybatis批量插入
    • 常规批量插入。(通过foreach,生成很长的SQL)
    • 使用ExecutorType.BATCH方式执行批量操作
  • 自动生成工具
  • Spring与mybatis结合

mybatis批量插入

常规批量插入。(通过foreach,生成很长的SQL)

速度快

    int batchInsertByNormal(List<Teacher> teacherList);
 List<Teacher> testData = new ArrayList<>();
    String[] tnameArr = new String[]{"四火", "四水", "四金", "四木", "四土"};

 // 构造测试数据
        for(int i = 0; i < 10000; i++) {
            Teacher teacher = new Teacher();
            int idx = random.nextInt(tnameArr.length);
            teacher.setTname(tnameArr[idx] +"_"+ (i + 1));
            teacher.setAge(i+1);
            testData.add(teacher);
 
    <insert id="batchInsertByNormal" parameterType="Teacher">
        insert into teacher (tname, age) values
        <foreach collection="list" item="teacher" separator="," close=";">
            (#{teacher.tname}, #{teacher.age})
        foreach>
    insert>
 /**
     * 常规批量插入。(通过foreach,生成很长的SQL)
     */
    @Test
    public void testBatchInsertByNormal() {
        long start = System.currentTimeMillis();
        int rows = teacherDao.batchInsertByNormal(testData);
        log.info("插入数据行数: " + rows+", 耗时: " + (System.currentTimeMillis() - start));
    }

使用ExecutorType.BATCH方式执行批量操作

速度慢

 /**
     * 使用ExecutorType.BATCH方式执行批量操作
     */
    @Test
    public void testBatchInsertByExecutorType() {
        SqlSessionFactory factory = MyBatisTools.getInstance().getSessionFactory();
        SqlSession sqlSession = factory.openSession(ExecutorType.BATCH, false);
        TeacherDao teacherDao = sqlSession.getMapper(TeacherDao.class);
        long start = System.currentTimeMillis();
        int rows = 0;
        int batchSize = 100;
        int count = 0;
        for(Teacher teacher : testData) {
            rows += teacherDao.insertTeacher(teacher);
            count ++;
            if(count % batchSize == 0) {
                sqlSession.flushStatements();
            }
        }
        sqlSession.flushStatements();
        sqlSession.commit();
        sqlSession.close();
        log.info("插入数据行数: " + rows+", 耗时: " + (System.currentTimeMillis() - start));
    }

自动生成工具

在maven项目的pox.xml引入依赖,位置:【build标签下】

in <plugins>
      <plug
in>
         <groupId>org.mybatis.generatorgroupId>
         <artifactId>mybatis-generator-maven-pluginartifactId>
        plugin>
    plugins>

在maven项目的pox.xml添加依赖,位置:【pluginManagement标签下的plugins内】

<plugin>                  					          <groupId>org.mybatis.generatorgroupId>
 <artifactId>mybatis-generator-maven-pluginartifactId>
  <version>1.3.5version>
   			<configuration>
                  <verbose>trueverbose>
                   <overwrite>trueoverwrite>
              configuration>
  plugin>

配置文件建在resources,文件名generatorContext.xml




<generatorConfiguration>

    
    <classPathEntry location="D:\Mavenpath\.m2\repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar" />

    
    <context id="localhost_mysql" targetRuntime="MyBatis3">

        
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        commentGenerator>

        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/bookasp?characterEncoding=utf8&serverTimezone=UTC"
                        userId="root"
                        password="root">
        jdbcConnection>

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

        
        <javaModelGenerator targetPackage="test.spring.bean" targetProject="src/main/java">
            <property name="enableSubPackages" value="false" />
            <property name="trimStrings" value="true" />
        javaModelGenerator>

        
        <sqlMapGenerator targetPackage="src/main/resources/mappers" targetProject=".">
            <property name="enableSubPackages" value="false" />
        sqlMapGenerator>

        
        
        <javaClientGenerator type="XMLMAPPER" targetPackage="test.spring.mapper"  targetProject="src/main/java">
            
            <property name="enableSubPackages" value="false" />
        javaClientGenerator>
		
        <table schema="bookasp" tableName="message" domainObjectName="Message"
               enableCountByExample="false">
            

            
            

            <generatedKey column="id" sqlStatement="mysql" identity="true" />

            
            
            
            
        table>
    context>
generatorConfiguration>

点击maven在Plugins下出现mybatis-generator

点开双击mybatis-generator:generate就可自动生成一些与数据库操作的代码代码

Spring与mybatis结合

使用步骤
添加依赖包

<dependency>
    <groupId>org.mybatisgroupId>
    <artifactId>mybatis-springartifactId>
    <version>2.0.1version>
dependency>

配置数据源

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="url" value="${jdbc.url}"/>
    <property name="driverClassName" value="${jdbc.driver}"/>
    <property name="username" value="${jdbc.user}"/>
    <property name="password" value="${jdbc.password}"/>
bean>

配置Spring、Mybatis整个的管理Bean

<bean class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    
	<property name="mapperLocations" value="classpath:/mapper/*"/>
bean>

通过mybatis scheme来自动扫描所有的Mapper接口

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       	http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
       	http://www.springframework.org/schema/context/spring-context.xsd
        http://mybatis.org/schema/mybatis-spring
        http://mybatis.org/schema/mybatis-spring.xsd">

    

    <mybatis:scan base-package="com.lanou3g.spring.mapper" />
beans>

你可能感兴趣的:(总结)