• SpringBoot整合Mybatis


    一、整合

    项目包结构如下图所示:

    这里写图片描述

    1、pom文件

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>BootProject</groupId>
      <artifactId>BootProject</artifactId>
      <version>0.0.1-SNAPSHOT</version>
    
      <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
        </parent>
        <!-- 管理版本 -->
        <properties>
            <java.version>1.8</java.version>
            <mybatis.version>3.2.6</mybatis.version> 
            <mysql.version>5.1.38</mysql.version>
            <mybatis.generator.version>1.3.2</mybatis.generator.version>        
        </properties>
        <dependencies>
            <!-- spring -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-jdbc</artifactId>
            </dependency>
            <!-- mybatis -->
                <dependency>  
                <groupId>org.mybatis</groupId>  
                <artifactId>mybatis</artifactId>  
                <version>${mybatis.version}</version>  
            </dependency>  
            <dependency>  
                <groupId>org.mybatis</groupId>  
                <artifactId>mybatis-spring</artifactId>  
                <version>1.2.2</version>  
            </dependency>  
            <!-- mybatis generator --> 
            <dependency>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-core</artifactId>
                <version>${mybatis.generator.version}</version>
                <scope>compile</scope>
                <optional>true</optional>
            </dependency>
            <!-- Mysql -->  
            <dependency>  
                <groupId>mysql</groupId>  
                <artifactId>mysql-connector-java</artifactId>  
                <version>${mysql.version}</version>  
            </dependency> 
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
                <version>1.4.0.RELEASE</version>
            </dependency>   
        </dependencies>
      <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
              <plugin>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-maven-plugin</artifactId>
                    <version>1.3.2</version>
                     <configuration>
                        <verbose>true</verbose>
                        <overwrite>true</overwrite>
                    </configuration>
                    <dependencies>
                        <dependency>
                            <groupId>mysql</groupId>
                            <artifactId>mysql-connector-java</artifactId>
                            <version>${mysql.version}</version>
                        </dependency>
                    </dependencies>
                </plugin>
        </plugins>
    </build>
    </project>

    注:这里没有采用通用mapper。

    2、generator生成实体和mapper

    注:这里采用pdm生成数据库表,根据表逆向工程生成实体和mapper文件。

    配置generatorConfig.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>
        <!-- 配置参数从properties中读取 -->
        <properties resource="generatorConfig.properties" />
        <context id="Mysql" targetRuntime="MyBatis3Simple">
          <commentGenerator>
            <property name="suppressAllComments" value="true"/>
          </commentGenerator>
          <!-- 数据库连接 -->
        <jdbcConnection driverClass="${jdbc.driverClass}"
            connectionURL="${jdbc.url}" userId="${jdbc.user}" password="${jdbc.password}">
        </jdbcConnection>
          <javaTypeResolver>
             <property name="forceBigDecimals" value="false"/>
          </javaTypeResolver>
          <!-- 实体 -->
          <javaModelGenerator targetPackage="com.mybatis.model" targetProject="src/main/java">
              <property name="enableSubPackages" value="true"/>
              <property name="trimStrings" value="true"/>
          </javaModelGenerator>
            <!-- mapper文件 -->      
          <sqlMapGenerator targetPackage="sqlmap" targetProject="src/main/resources">
               <property name="enableSubPackages" value="true"/>
          </sqlMapGenerator>   
          <!-- mapper接口 --> 
          <javaClientGenerator type="XMLMAPPER" targetPackage="com.mybatis.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
          </javaClientGenerator>
          <!-- tableName表名,domainObjectName实体名 -->
          <table  tableName="t_User" domainObjectName="User" enableCountByExample="false" enableSelectByExample="false" enableUpdateByExample="false" enableDeleteByExample="false">
    
          </table>
        </context>
    
        </generatorConfiguration>

    generatorConfig.properties

    jdbc.driverClass = com.mysql.jdbc.Driver
    jdbc.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
    jdbc.user = root
    jdbc.password = root
    mapper.plugin = tk.mybatis.mapper.generator.MapperPlugin
    mapper.Mapper = tk.mybatis.mapper.common.Mapper

    执行maven命令:mybatis-generator:generate,刷新项目即可。

    3、注入mapper接口代理

    /** 
     * @author  saixing_yang@hiersun.com
     * @date 创建时间:2016年12月21日 下午4:35:59 
     * @version 1.0 
     */
    @Configuration  //刷新配置信息 boot会自动注入datasource,但mapper的路径需要手动注入
    @EnableTransactionManagement // 启注解事务管理,等同于xml配置方式的 <tx:annotation-driven />
    public class MybatisConfig implements TransactionManagementConfigurer {
        @Autowired
        private DataSource dataSource;
    
        @Bean(name = "sqlSessionFactory")
        public SqlSessionFactory sqlSessionFactory() throws Exception {
            SqlSessionFactoryBean bean =new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            bean.setMapperLocations(new PathMatchingResourcePatternResolver().
                    getResources("classpath:com/common/dao/mapper/UserMapper.xml"));    
            return bean.getObject();
        }
        @Bean
        public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    
        @Override
        public PlatformTransactionManager annotationDrivenTransactionManager() {
            return new DataSourceTransactionManager(dataSource);
        }
    }
    

    MybatisMapperScannerConfig 自动扫描配置

    @Configuration
    public class MybatisMapperScannerConfig {
        @Bean
        public MapperScannerConfigurer mapperScannerConfigurer() {
            MapperScannerConfigurer scanner = new MapperScannerConfigurer();
            scanner.setSqlSessionFactoryBeanName("sqlSessionFactory");  //set 手动配置的sqlSessionFactory
            scanner.setBasePackage("com.common.dao");
            return scanner;
        }
    }

    二、常见问题

    SpringBoot扫描包问题

    报错信息:Consider defining a bean of type in your configuration

    方法一:

    使用注解 @ComponentScan(value=”com.common”),其中,com.common为包路径。

    方法二:
    将启动类Application放在上一级包中。
    如下图所示:
    这里写图片描述

    三、总结

    SpringBoot使得开发效率大大提升,我们不再需要写一堆繁琐的配置文件来说明类与类的关系。取而代之的是,我们只需要关心如何让一个Bean可以被springboot扫描到就好了。

    嘿嘿,这感觉好像你之前要自己去超市购物,然后带回家。现在有人帮你买了拿回来,但你需要把你家的地址告诉他,然后你就可以省出很多时间做其他的事情了。

  • 相关阅读:
    微软职位内部推荐-SENIOR SDE
    微软职位内部推荐-Senior Network Engineer
    微软职位内部推荐-Principal Dev Manager
    微软职位内部推荐-SDE II
    微软职位内部推荐-Sr DEV
    【转载】NIO服务端序列图
    【转载】NIO客户端序列图
    同步与异步
    Linux查找命令
    Spring中Bean的实例化
  • 原文地址:https://www.cnblogs.com/saixing/p/6730193.html
Copyright © 2020-2023  润新知