springboot 配置mybatis通用mapper

声明:

此处为springboot 配置mybatis的通用mapper方

一共步其他多余操作不要有

1添加mapper依赖

一定要有以下依赖的jar包

注意jar包版本,太高会导致功能不可用

 
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            ${mybatis-spring-boot}
        
        
            tk.mybatis
            mapper-spring-boot-starter
            1.1.7
        
        
            tk.mybatis
            mapper
            3.4.6
        

        
            javax.persistence
            persistence-api
            1.0
        

2application.yml.文件

配置数据源,myabtis  logging和elastic-job可忽略

spring:
  datasource:
    jdbc-url: jdbc:mysql://172.20.94.39:3306/marketing?characterEncoding=utf-8&verifyServerCertificate=false&useSSL=false&requireSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: marketing
    password: marketing
    type: com.zaxxer.hikari.HikariDataSource
mybatis:
  type-aliases-package: com.renrenche.marketing.ads_scheduler.domain
#  mapper-locations: classpath:mapper/*.xml


logging:
  config: classpath:log4j2-development.yml

elastic-job:
  zookeeper-servers: 172.20.94.39:2181
  namespace: marketing-ads-scheduler


3编写MyMapper通用工具类 放在util包下,不要与正常的dao层mapper放到一起!!!

package com.renrenche.marketing.ads_scheduler.common.utils;

/**
 * Created by Administrator on 2017/8/4.
 */

import tk.mybatis.mapper.common.ConditionMapper;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
import tk.mybatis.mapper.common.special.InsertListMapper;

/**
 * 继承自己的MyMapper
 *
 * @author junwen
 * @since 2017年8月22日11:50:27
 */
public interface MyMapper extends Mapper,
        MySqlMapper,
        ConditionMapper,
        InsertListMapper {

    //TODO
    //FIXME 特别注意,该接口不能被扫描到,否则会出错
}

4配置mapper配置文件

package com.renrenche.marketing.ads_scheduler.config;

import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

@Configuration
public class MapperConfig {
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        mapperScannerConfigurer.setBasePackage("com.renrenche.marketing.ads_scheduler.dao");//扫描该路径下的dao
        Properties properties = new Properties();
        properties.setProperty("mappers", "com.renrenche.marketing.ads_scheduler.common.utils.MyMapper");//通用dao
        properties.setProperty("notEmpty", "false");
        properties.setProperty("IDENTITY", "MYSQL");
        mapperScannerConfigurer.setProperties(properties);
        return mapperScannerConfigurer;
    }

}

 

5不需要在启动类上添加@MapperScan注解
6不需要在application.yml文件添加mapper配置

配好之后使用方法    dao.select()无报错并有返回值就代表已经配好了。
通用mapper的好处,可以省区增删改查的代码开发,加快开发速度,有很好的通用方法。省去一些值需要写简单增删改查的xml文件。

你可能感兴趣的:(springboot)