SpringBoot+MyBatis通用Mapper3实践浅析

阿里巴巴长期招聘Java研发工程师p6,p7,p8等上不封顶级别,有意向的可以发简历给我,注明想去的部门和工作地点:[email protected]

欢迎关注微信公众号:技术原始积累 获取更多技术干货

一、前言

MyBatis通用Mapper3是对mybaits的数据库操作的一层封装,之前使用时候是根据数据库表生成mapper.xml,mapper的接口类,这个mapper.xml和接口类被代理后生成能够操作数据对应表的基础功能,而Mapper3则是对其封装,基础功能不在需要mapper.xml,接口类只需要继承封装好的Mapper接口就具有了操表的基础功能,如果你需要自己的操作则还是需要在mapper.xml中和接口类中写实现。Mapper3项目地址:http://git.oschina.net/free/Mapper

二、如何使用

2.1 引入maven配置

SpringBoot应用只需要引入:



    org.mybatis.spring.boot
    mybatis-spring-boot-starter
    1.1.1



    tk.mybatis
    mapper-spring-boot-starter
    1.1.0



    com.github.pagehelper
    pagehelper-spring-boot-starter
    1.1.0

2.2 generator 生成基础文件

在src/main/resources下面
generator.xml文件



//属性值,下面的config.properties文件
  

  
    
    
    //插件
    
      
    

  //数据源
    
    

//Do生成
    
//mapper xml文件
    
//mapper接口文件
    


cofing.properties文件

jdbc.driverClass = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://1270.0.1:3308/db
jdbc.user = ****
jdbc.password =****

jdbc.maxPoolSize=50
jdbc.minPoolSize=10
jdbc.maxStatements=100
jdbc.testConnection=true

# 插件
mapper.plugin = tk.mybatis.mapper.generator.MapperPlugin
mapper.Mapper = tk.mybatis.mapper.common.Mapper

然后在pom.xml配置如下:


        
        
        ${basedir}/src/main/java
        com.zlx.demo.web.speech.mapper
        com.zlx.alin.demo.speech.model
        
        ${basedir}/src/main/resources
        mapper
        3.4.2
        3.4.1.snapshot
        5.1.30
        1.2.4
    


                org.mybatis.generator
                mybatis-generator-maven-plugin
                1.3.2
                
                    ${basedir}/src/main/resources/generator/generatorConfig.xml
                    true
                    true
                
                
                    
                        mysql
                        mysql-connector-java
                        ${mysql.version}
                    
                    
                        tk.mybatis
                        mapper
                        ${mapper.version}
                    
                
            

然后在pom所在目录执行:mvn mybatis-generator:generate 即可
生成的Mapper接口文件:

public interface SwardManMapper extends Mapper{


}

生成的Mapper.xml文件(里面没有任何操作):




    
    
    
    
  

生成的Do文件:

@Table(name="lassen_swardman")
public class SwardManDo {

    
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private Integer    guild_id;
    private String creator;
    private String modifier;
    private String name;
    private String status;
    private Date   gmt_create;
    private Date   gmt_modified;
    private String is_deleted;
    private Integer     power;
    
    
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    public String getModifier() {
        return modifier;
    }
    public void setModifier(String modifier) {
        this.modifier = modifier;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public Date getGmt_create() {
        return gmt_create;
    }
    public void setGmt_create(Date gmt_create) {
        this.gmt_create = gmt_create;
    }
    public Date getGmt_modified() {
        return gmt_modified;
    }
    public void setGmt_modified(Date gmt_modified) {
        this.gmt_modified = gmt_modified;
    }
    public String getIs_deleted() {
        return is_deleted;
    }
    public void setIs_deleted(String is_deleted) {
        this.is_deleted = is_deleted;
    }
    public Integer getPower() {
        return power;
    }
    public void setPower(Integer power) {
        this.power = power;
    }
    public Integer getGuild_id() {
        return guild_id;
    }
    public void setGuild_id(int guild_id) {
        this.guild_id = guild_id;
    }
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }

}

2.3 测试

@RestController
@RequestMapping(value = "/speech/test")
public class TestRpc {
    
    @Autowired
    SwardManMapper swardManMapper;

    @RequestMapping(value = "selectAll", method = { RequestMethod.GET, RequestMethod.POST })
    public DecorateActionResult selectAll() {
        ActionResult result = new ActionResult();
        DecorateActionResult resultNew = new DecorateActionResult();
        resultNew.setContent(result);
        try {

            result.setRetValue(swardManMapper.selectAll());

        } catch (Exception ee) {
            result.setErrorMessage(ee.getLocalizedMessage());
            resultNew.setHasError(true);
        }

        return resultNew;
    }
}

三、原理分析

一切的不同在于mapper接口类继承了Mapper,所以分析其原理自然是看看Mapper干了啥:

public interface Mapper extends
        BaseMapper,
        ExampleMapper,
        RowBoundsMapper,
        Marker {
}

public interface BaseMapper extends
        BaseSelectMapper,
        BaseInsertMapper,
        BaseUpdateMapper,
        BaseDeleteMapper {

}

public interface BaseSelectMapper extends
        SelectOneMapper,
        SelectMapper,
        SelectAllMapper,
        SelectCountMapper,
        SelectByPrimaryKeyMapper,
        ExistsWithPrimaryKeyMapper {

}

public interface SelectAllMapper {

    /**
     * 查询全部结果
     *
     * @return
     */
    @SelectProvider(type = BaseSelectProvider.class, method = "dynamicSQL")
    List selectAll();
}

一层层继承后找到了上面调用的selectAll的定义,原来使用的是SelectProvider注解,再看下selectAll的实现类BaseSelectProvider

public class BaseSelectProvider extends MapperTemplate {

    public BaseSelectProvider(Class mapperClass, MapperHelper mapperHelper) {
        super(mapperClass, mapperHelper);
    }

   ...........
    /**
     * 查询
     *
     * @param ms
     * @return
     */
    public String selectOne(MappedStatement ms) {
        Class entityClass = getEntityClass(ms);
        //修改返回值类型为实体类型
        setResultType(ms, entityClass);
        StringBuilder sql = new StringBuilder();
        sql.append(SqlHelper.selectAllColumns(entityClass));
        sql.append(SqlHelper.fromTable(entityClass, tableName(entityClass)));
        sql.append(SqlHelper.whereAllIfColumns(entityClass, isNotEmpty()));
        return sql.toString();
    }


    /**
     * 查询全部结果
     *
     * @param ms
     * @return
     */
    public String selectAll(MappedStatement ms) {
        final Class entityClass = getEntityClass(ms);
        //修改返回值类型为实体类型
        setResultType(ms, entityClass);
        StringBuilder sql = new StringBuilder();
        sql.append(SqlHelper.selectAllColumns(entityClass));
        sql.append(SqlHelper.fromTable(entityClass, tableName(entityClass)));
        sql.append(SqlHelper.orderByDefault(entityClass));
        return sql.toString();
    }
}

至此大概知道了是怎么玩的了,这些函数里面是拼接sql语句的。所以如果需要我们可以重写这些SelectProvider实现自己的逻辑,比如查找时候之筛选is_deleted='n'的等等。

欢迎关注微信公众号:技术原始积累 获取更多技术干货

image.png

你可能感兴趣的:(SpringBoot+MyBatis通用Mapper3实践浅析)