Spring boot + mybatis complete configuration process + mybatis experience (transfer)

In the team, most developers now like to use mybatis, because mybatis is based on sql and can be written by basically seeing how to write sql, which is relatively easy to use. Therefore, the framework construction of this spring boot+mybatis was born. (Actually, I prefer to think that jpa is more concise and easy to use. I think jpa + idea + spring loader is the fastest way to develop = =! I don't like to use eclipse and feel that it is a bit troublesome to engage in terminal. Next time, I will write the completed configuration of jpa and spring boot. process and usage)

mybatis has many advantages.
  1. Easy to pick up and master.
  2. SQL is written in xml, which is convenient for unified management and optimization.
  3. Decouple SQL from program code.
  4. Provides a mapping label to support the orm field relationship mapping between objects and databases
  5. Provide object-relational mapping labels to support the maintenance of object-relationships
  6. Provides xml tags to support writing dynamic sql.
Disadvantages: The author summarizes it by himself (it is recommended to use annotations and sql builder to write mybatis, if you use xml, there will be some troubles.)
  1. In fact, there are still some inconvenient places in the development process, which are listed below. Most people are used to the xml form. spring loader does not support hot deployment of xml. If written to the sql builder. It is through java code to build sql and many people don't know much about it. So, you need to restart once you change it. It's a bit of a hassle. (I don't like doing things that waste time.)
  2. That is, mybatis writes a query statement for one entity at a time. It is necessary to establish a mapper and xml for mapping. In this way, there are more and more Mappers and more and more xml. Feeling bad to manage, = =! .

Enter the text below. That is, spring boot configures mybatis.

  1. Configure the datasource into the ioc container (this includes the loading of application.propertits, you can refer to the children's shoes just getting started).
  2. Configure @MapperScan('package name') Configure mapper scan path. According to my understanding, this is to generate beans for mapper and put them in the ioc container.
@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. Configure the mybatis-config path, xml mapper path, and typeAlias ​​path (the corresponding class name is lowercase), according to the mybatis official website is to build 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. Finally, post the configuration of mybatis-config.xml (please remember to configure the hump naming conversion, otherwise the hump naming nest will not be possible).

<?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. The author gives the configuration of 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. Finally open your terminal; input, gradle bootRun and enjoy the fun of writing code.

  1. In the end, the author still feels that mybatis is more cumbersome. Compared to jpa and hibernate. = = ! Maybe I haven't gone deep into the bottom layer of mybatis. I hope you can guide me.



Text/Zeroff (author of Jianshu)
original link: http://www.jianshu.com/p/69b9fbb97574
The copyright belongs to the author, please contact the author for authorization, and mark "author of Jianshu".

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327064226&siteId=291194637