springboot 集成mybatis3.4.5 mapper tk.mybatis

时光毁灭记忆、已成空白 提交于 2020-08-17 20:10:49

本篇主要介绍的是springboot如何集成mybatis,以及一些常用的mapper编写,与顶层tk.mybatis的mapper结合集成,看懂之后即可快速的开发

1、配置sqlSessionFactory

import com.gta.train.platform.persis.page.plugin.PageInterceptor;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
@EnableTransactionManagement
@RequiredArgsConstructor
public class MyBatisConfig implements TransactionManagementConfigurer {

    private final DataSource dataSource;

    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        bean.setMapperLocations(resolver.getResources("classpath*:/mapper/**/**.xml"));
        bean.setTypeAliasesPackage("xx.entity");
        Interceptor pageInterceptor = new PageInterceptor();
        Interceptor[] plugins = {pageInterceptor};
        bean.setPlugins(plugins);
        try {
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Bean
    public PlatformTransactionManager txManager() {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
 

2、定义常用接口

import org.apache.ibatis.mapping.MappedStatement;

import xx.MapperException;

import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;
import tk.mybatis.mapper.mapperhelper.SqlHelper;

import java.util.Set;

/**
 * 通过 ids 字符串的各种操作
 * <p/>
 * ids 如 "1,2,3"
 */
public class IdsProvider extends MapperTemplate {

    public IdsProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
        super(mapperClass, mapperHelper);
    }

    /**
     * 根据主键字符串进行删除,类中只有存在一个带有@Id注解的字段
     */
    public String deleteByIds(MappedStatement ms) {
        final Class<?> entityClass = getEntityClass(ms);
        StringBuilder sql = new StringBuilder();
        sql.append(SqlHelper.deleteFromTable(entityClass, tableName(entityClass)));
        Set<EntityColumn> columnList = EntityHelper.getPKColumns(entityClass);
        if (columnList.size() == 1) {
            EntityColumn column = columnList.iterator().next();
            sql.append(" where ");
            sql.append(column.getColumn());
            sql.append(" in (${_parameter})");
        } else {
            throw new MapperException(
                "继承 deleteByIds 方法的实体类[" + entityClass.getCanonicalName() + "]中必须只有一个带有 @Id 注解的字段");
        }
        return sql.toString();
    }

    /**
     * 根据主键字符串进行查询,类中只有存在一个带有@Id注解的字段
     */
    public String selectByIds(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)));
        Set<EntityColumn> columnList = EntityHelper.getPKColumns(entityClass);
        if (columnList.size() == 1) {
            EntityColumn column = columnList.iterator().next();
            sql.append(" where ");
            sql.append(column.getColumn());
            sql.append(" in (${_parameter})");
        } else {
            throw new MapperException(
                "继承 selectByIds 方法的实体类[" + entityClass.getCanonicalName() + "]中必须只有一个带有 @Id 注解的字段");
        }
        return sql.toString();
    }

    /**
     * 只更新is_del字段为1 主键不存在 不会更新记录
     */
    public String deleteLogic(MappedStatement ms) {
        Class<?> entityClass = getEntityClass(ms);
        return SqlHelper.updateTable(entityClass, tableName(entityClass)) +
            SqlHelper.updateSetColumns(entityClass, null, true, isNotEmpty()) +
            SqlHelper.wherePKColumns(entityClass);
    }
}
 

 

import org.apache.ibatis.annotations.SelectProvider;

import xx.persis.mybatis.plugin.ids.provider.IdsProvider;

import java.util.List;

/**
 * 通用Mapper接口,根据ids查询
 * @param <T> 不能为空
 */
public interface SelectByIdsMapper<T> {

    /**
     * 根据主键字符串进行查询,类中只有存在一个带有@Id注解的字段
     * @param ids 如 "1,2,3,4"
     */
    @SelectProvider(type = IdsProvider.class, method = "dynamicSQL")
    List<T> selectByIds(String ids);

}

 

import org.apache.ibatis.annotations.DeleteProvider;

import xx.persis.mybatis.plugin.ids.provider.IdsProvider;

/**
 * 通用Mapper接口,根据ids删除
 * @param <T> 不能为空
 */
public interface DeleteByIdsMapper<T> {

    /**
     * 根据主键字符串进行删除,类中只有存在一个带有@Id注解的字段
     * @param ids 如 "1,2,3,4"
     */
    @DeleteProvider(type = IdsProvider.class, method = "dynamicSQL")
    int deleteByIds(String ids);

}
 

/**
 * 通用Mapper接口,根据ids操作
 * @param <T> 不能为空
 */
public interface IdsMapper<T> extends SelectByIdsMapper<T>, DeleteByIdsMapper<T> {

}

 

import xx.persis.mybatis.plugin.baseopt.interfaces.BaseLogicDel;
import xx.persis.mybatis.plugin.ids.IdsMapper;
import xx.persis.mybatis.plugin.ids.provider.DeleteLogicProvider;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.UpdateProvider;
import tk.mybatis.mapper.additional.insert.InsertListMapper;
import tk.mybatis.mapper.common.Mapper;

/**
 * 
 * FunctionMapper集成了MySQL所使用的绝大部分Mapper了,也可以很好的进行扩展
 */
public interface FunctionMapper<T> extends Mapper<T>, InsertListMapper<T>, IdsMapper<T> {

    /**
     * 通过id逻辑删除
     */
    @UpdateProvider(type = DeleteLogicProvider.class, method = "dynamicSQL")
    @Options(useCache = false)
    int deleteLogic(BaseLogicDel model);

    /**
     * 通过ids数组逻辑删除
     */
    @UpdateProvider(type = DeleteLogicProvider.class, method = "dynamicSQL")
    @Options(useCache = false)
    int deleteLogicList(String[] ids);
}
 

3、配置MapperScannerConfigurer

 

import xx.FunctionMapper;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import java.util.Properties;

@Configuration
@Component
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {// Environment env
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        mapperScannerConfigurer.setBasePackage("xx.dao");
        mapperScannerConfigurer.setMarkerInterface(FunctionMapper.class);
        Properties properties = new Properties();
        properties.setProperty("notEmpty", "true");
        properties.setProperty("ORDER", "BEFORE");
        mapperScannerConfigurer.setProperties(properties);
        return mapperScannerConfigurer;
    }

}

 

 


 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!