美文网首页spring 源码剖析mybatis程序员的生活感悟
spring boot + mybatis 完整配置过程+myb

spring boot + mybatis 完整配置过程+myb

作者: Rick____ | 来源:发表于2016-06-25 00:06 被阅读78157次

    在团队里面现在大多数开发者都喜欢用mybatis,因为mybatis 基于sql 基本上看下sql 怎么写就能写出来,算是比较容易上手。因此就萌生了这个spring boot+mybatis的框架构建。(其实笔者更喜欢觉得jpa 更加简洁容易上手 我认为jpa + idea + spring loader 才是开发最快的= = !笔者不喜欢用eclipse 觉得搞terminal有点麻烦,下次写上jpa和spring boot 的完成配置过程和使用方法)

    mybatis有很多优点。
    1. 易于上手和掌握。
    1. sql写在xml里,便于统一管理和优化。
    2. 解除sql与程序代码的耦合。
    3. 提供映射标签,支持对象与数据库的orm字段关系映射
    4. 提供对象关系映射标签,支持对象关系组建维护
    5. 提供xml标签,支持编写动态sql。
    缺点:笔者自己总结了下(建议使用注解和sql 构建器来写mybatis ,如果使用xml 就会有一些麻烦事了。)
    1. 其实在开发过程中还是有一些不方便的地方以下列成几种。大多数人习惯于xml 形式。spring loader 不支持热部署xml 的。如果写入sql 构建器。就是通过java 代码来构建sql 又很多人不是特别了解。所以,你改一次就要重启。就有点麻烦了。(笔者最不喜欢就是干浪费时间的事了。)
    1. 就是mybatis 每次写一个实体的查询语句。就要建立一个mapper 和xml 进行映射。这样Mapper越来越多和xml 越来越多。感觉不好管理,= = !。

    下面进入正文。就是spring boot 配置mybatis 了。

    1. 配置datasource 到ioc 容器里面 (这里包括application.propertits 的加载,各位刚入门的童鞋可以参照参照),本文是默认的spring boot dataSource .所以可以直接注入给mybatis 即可。
    2. 配置@MapperScan('package name') 配置mapper 扫描路径。这个按照我的理解就是为mapper 产生bean 放进ioc 容器内。
    @Configuration
    @MapperScan("com.aoshi.dao")
    public class MyBatisConfig {    
    }
    

    3 . 配置mybatis-config 路径,xml mapper 路径, 和typeAlias 路径(对应类名小写的),根据mybatis 官网就是构建SqlSessionFactoryBean。

    
    @Configuration
    @Mapper
    public class SessionFactoryConfig {    
            /**   mybatis 配置路径     */    
            private static String MYBATIS_CONFIG = "mybatis-config.xml";    
            /**   mybatis mapper resource 路径     */    
            private static String MAPPER_PATH = "/mapper/**.xml";    
    
            @Autowired    
            private DataSource dataSource;
        
            private String typeAliasPackage = "com.aoshi.domain";   
    
            /** 
              *创建sqlSessionFactoryBean 实例     
              * 并且设置configtion 如驼峰命名.等等     
              * 设置mapper 映射路径     
              * 设置datasource数据源     
              * @return     
              */
            @Bean    
            public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();        
            /** 设置mybatis configuration 扫描路径 */                
            sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(MYBATIS_CONFIG));
            /** 添加mapper 扫描路径 */        
             PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();        
             String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + MAPPER_PATH;
             sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath));
            /** 设置datasource */        
             sqlSessionFactoryBean.setDataSource(dataSource);   
            /** 设置typeAlias 包扫描路径 */     
             sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasPackage);        
             return sqlSessionFactoryBean;    
              }
    }
    

    4 . 最后贴出mybatis-config.xml 的配置(小伙伴记得配置上驼峰命名转换否则无法驼峰命名窝)。

    <?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="cacheEnabled" value="true"/>        
                    <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 -->        
                    <setting name="lazyLoadingEnabled" value="true"/>        
                    <!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载。 -->        
                    <setting name="aggressiveLazyLoading" value="true"/>        
                    <!-- 是否允许单条sql 返回多个数据集  (取决于驱动的兼容性) default:true -->        
                    <setting name="multipleResultSetsEnabled" value="true"/>        
                    <!-- 是否可以使用列的别名 (取决于驱动的兼容性) default:true -->        
                    <setting name="useColumnLabel" value="true"/>        
                    <!-- 允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。  default:false  -->        
                    <setting name="useGeneratedKeys" value="true"/>        
                    <!-- 指定 MyBatis 如何自动映射 数据基表的列 NONE:不隐射 PARTIAL:部分  FULL:全部  -->        
                    <setting name="autoMappingBehavior" value="PARTIAL"/>        
                    <!-- 这是默认的执行类型  (SIMPLE: 简单; REUSE: 执行器可能重复使用prepared statements语句;BATCH: 执行器可以重复执行语句和批量更新)  -->        
                    <setting name="defaultExecutorType" value="SIMPLE"/>        
                    <!-- 使用驼峰命名法转换字段。 -->        
                    <setting name="mapUnderscoreToCamelCase" value="true"/>        
                    <!-- 设置本地缓存范围 session:就会有数据的共享  statement:语句范围 (这样就不会有数据的共享 ) defalut:session -->        
                    <setting name="localCacheScope" value="SESSION"/>        
                    <!-- 设置但JDBC类型为空时,某些驱动程序 要指定值,default:OTHER,插入空值时不需要指定类型 -->        
                    <setting name="jdbcTypeForNull" value="NULL"/>    
             </settings>    
            <plugins>        
                    <plugin interceptor="com.github.pagehelper.PageHelper">            
                            <property name="dialect" value="mysql"/>            
                            <property name="offsetAsPageNum" value="false"/>            
                            <property name="rowBoundsWithCount" value="false"/>            
                            <property name="pageSizeZero" value="true"/>            
                            <property name="reasonable" value="false"/>            
                            <property name="supportMethodsArguments" value="false"/>            
                            <property name="returnPageInfo" value="none"/>        
                   </plugin>    
          </plugins>
    </configuration>
    

    5 . 笔者给出gradle.build 的配置

    dependencies {    
            compile fileTree(dir: 'lib', includes: ['*.jar'])    
            compile 'org.springframework.boot:spring-boot-starter-web'    
            compile 'org.springframework.boot:spring-boot-devtools'    
            compile 'org.springframework.boot:spring-boot-starter-thymeleaf'//    
            compile 'org.springframework.boot:spring-boot-starter-security'    
            compile 'org.springframework.boot:spring-boot-starter-redis'//    
            compile 'org.springframework.session:spring-session:1.2.0.RELEASE'//    
            compile "org.springframework.security.oauth:spring-security-oauth2"    
            compile 'mysql:mysql-connector-java'    
            /** 配置mybatis 数据源  */    
            compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:1.1.1")    
            /** mybatis分页插件 */    
            compile 'com.github.pagehelper:pagehelper:4.1.6'    /** -Swagger */    
            compile("io.springfox:springfox-swagger-ui:2.2.2")    
            compile("io.springfox:springfox-swagger2:2.2.2")    testCompile 'org.springframework.boot:spring-boot-starter-test'    
            /** http 请求类*/    
            compile 'httpcomponents-httpcore:httpcore:4.0-alpha6'    
            compile 'org.apache.httpcomponents:httpmime:4.5.2'    
            compile 'commons-httpclient:commons-httpclient:3.1'    
            compile 'dom4j:dom4j:1.6.1'//    
    
    1. application.properties spring boot 的dataSource配置
    spring.datasource.url=<url>
    spring.datasource.username=<userName>
    spring.datasource.password=<password>
    spring.datasource.driverClassName=com.mysql.jdbc.Driver
    
    

    7 . 最后open your terminal;input ,gradle bootRun 享受写代码带来的乐趣吧。

    1. 最后的最后笔者还是觉得mybatis 是比较繁琐的。比起jpa 跟hibernate 来说的话。= = !可能我还没有深入到mybatis 的底层里面吧。希望各位大神指导。

    相关文章

      网友评论

      • zw900808:为什么没有事务,mybatis配置不加事务吗
        Rick____:@zw900808 不用。加个注解可以的。
        zw900808:@Rick____ 要做配置吗,我是初学者按照你的代码都配置好了,就是发现没事务所以过来问问
        Rick____:@zw900808 事务spring 有http://spring.io/guides/gs/managing-transactions/ 我就直接用了
      • 何曾_9ce3:我想问个问题,就是在 mybatis中的mapper.xml中写了批量插入语句,如何spring boot的mapper接口中如何去调用这个语句???? 在线等 ....谢谢
        Rick____:@何曾_9ce3 这个跟你的映射关系没关系,应该是你的依赖注入出现了问题。很有可能是你注入的方式不对?
        何曾_9ce3:@Rick____ 你给的链接,我有看过,我有在service中继承那个SqlSessionDaoSupport 但是我启动项目的时候就报错,报org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'showController': Unsatisfied dependency expressed through field 'showService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException
        Rick____:应该跟普通插入一样吧。不知道有没有理解错误。id对应就可以了。 参考下这个链接。 http://chenzhou123520.iteye.com/blog/1583407/
      • Winter_Chen:为什么mybatis配置不使用yml的方式?这样写特别麻烦吧
        Rick____:@埃尔文放弃 yml确实是比较方便,这份配置是那时候官网的配置。
      • 清墨无痕:通过注解的方式写sql基本是满足的,但是遇到分页和动态sql就要提高偶外类配合,而且也不容易发现错误,不利于观察和优化
        Rick____:@作死加班狗 额。可以有。但是貌似很多都要定制resultmap。要不效率非常的低。
        作死加班狗:@ZeroFF 可以引入通用mapper这个项目。。。基本上满足大部分不写xml不写注解的sql了
        Rick____:@那年未见陌生 这是mybatis 很不方便的地方。打算写一个动态sql的工具。

      本文标题:spring boot + mybatis 完整配置过程+myb

      本文链接:https://www.haomeiwen.com/subject/efxadttx.html