`
frank1998819
  • 浏览: 731220 次
  • 性别: Icon_minigender_1
  • 来自: 南京
文章分类
社区版块
存档分类

spring boot + mybatis 完整配置过程+mybatis 体会(转)

 
阅读更多

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

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

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

  1. 配置datasource 到ioc 容器里面 (这里包括application.propertits 的加载,各位刚入门的童鞋可以参照参照)。
  2. 配置@MapperScan('package name') 配置mapper 扫描路径。这个按照我的理解就是为mapper 产生bean 放进ioc 容器内。
@Configuration
@MapperScan("com.aoshi.dao")
public class MyBatisConfig {    
private static final Logger logger = LoggerFactory.getLogger(MyBatisConfig.class);    @Autowired    private JdbcConfig jdbcConfig;
    @Bean    
public DataSource createDataSource() throws SQLException {      
        return DataSourceBuilder.create(Thread.currentThread().getContextClassLoader())
                                      .driverClassName(jdbcConfig.getDriverClass())                
                                      .url(jdbcConfig.url)                
                                      .username(jdbcConfig.userName)             
                                      .password(jdbcConfig.password).build();
    }    
@PropertySource(value = "application-dev.properties")    
@Component    
static class JdbcConfig {       
 /**         * 数据库用户名         */        
        @Value("${spring.datasource.username}")        
        private String userName;        
        /**         * 驱动名称         */        
        @Value("${spring.datasource.driverClassName}")        
        private String driverClass;        
        /**         * 数据库连接url         */        
        @Value("${spring.datasource.url}")        
        private  String url;        
        /**         * 数据库密码         */        
        @Value("${spring.datasource.password}")        
        private String password;        
        public String getUserName() {            return userName;        }  
        public void setUserName(String userName) {            this.userName = userName;        }        
        public String getDriverClass() {            return driverClass;        }                
        public void setDriverClass(String driverClass) {            this.driverClass = driverClass;        }        
        public String getUrl() {            return url;        }        
        public void setUrl(String url) {            this.url = url;        }                
        public String getPassword() {            return password;        }          
        public void setPassword(String password) {            this.password = password;        }    }}

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

@Configuration
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'//

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

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



文/Zeroff(简书作者)
原文链接:http://www.jianshu.com/p/69b9fbb97574
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics