精华内容
下载资源
问答
  • 这个项目采用的是springboot+tk.mybatis+sqlserver(可以切换至mysql) 其中对service层进行了封装,将Mapper baseMapper封装作为service层的一个对象,而其他映射到Mapper.xml的文件 则是针对特殊需求使用 可以通过...
  • tk-mybatis-dynamic-tablename tk.mybatis动态表操作
  • spring-boot+tk.mybatis通用mapper
  • spring4.0 集成 tk.mybatis插件,增删改无需增删改查,快速开发
  • springboot+springMVC+tk.mybatis+lombook+yml配置+logback-spring日志配置+ueditor源码修改整合 经测试有效,内附数据库文件及测试账号数据,在项目/doc文件夹中
  • 开发工具:IDEA 简介:使用SpringBoot+tk.Mybatis+Maven搭建的项目demo,可供参考和交流学习。项目文章:https://blog.csdn.net/fakerswe/article/details/80910035
  • 微服务框架SpringBoot+通用Mapper(tk.Mybatis)整个项目架构,直接上手开用,yml和logback配置都已经配置完好
  • 主要介绍了tk.mybatis扩展通用接口使用详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
  • 引入依赖和tk.mybatis <!--tk.mybatis--> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>3.4.2</version> </...

    搭建

    目录如下:
    在这里插入图片描述

    引入依赖和tk.mybatis

        <!--tk.mybatis-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>1.1.3</version>
        </dependency>
    

    完整的pom

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.4.1</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.redis</groupId>
        <artifactId>demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>redis-demo</name>
        <description>Demo project for Spring Boot</description>
    
    <properties>
        <java.version>1.8</java.version>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    
        <!--日志-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.21</version>
        </dependency>
    
    
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.4</version>
        </dependency>
    
    
    
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>
    
    
        <!--tk.mybatis-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>1.1.3</version>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    </project>
    

    配置类

    import java.util.Properties;
    import javax.sql.DataSource;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
    import org.springframework.core.io.support.ResourcePatternResolver;
    import tk.mybatis.spring.mapper.MapperScannerConfigurer;
    
    
    /**
     * Mybatis & Mapper & PageHelper 配置
     */
    @Configuration
    public class MybatisConfigurer {
        public static final String MAPPER_INTERFACE = "com.redis.demo.common.mapper.Dao";//Mapper插件基础接口的完全限定名,该接口需要自己定义
        public static final String BASE_PACKAGE = "com.redis.demo.**.dao";//Mapper插件基础接口的完全限定名
    
        @Bean
        public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
            SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
            factory.setDataSource(dataSource);
            factory.setTypeAliasesPackage("com.redis.demo.**.entity");
    
            //配置分页插件,详情请查阅官方文档(pageHelperStarter中已自动配置,此处配置会重复)
            //PageInterceptor pageInterceptor = new PageInterceptor();
            //Properties properties = new Properties();
            //properties.setProperty("pageSizeZero", "true");//分页尺寸为0时查询所有纪录不再执行分页
            //properties.setProperty("reasonable", "true");//页码<=0 查询第一页,页码>=总页数查询最后一页
            //properties.setProperty("supportMethodsArguments", "true");//支持通过 Mapper 接口参数来传递分页参数
            //pageInterceptor.setProperties(properties);
    
            //添加插件
            //factory.setPlugins(new Interceptor[]{pageInterceptor});
    
            //添加XML目录
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            factory.setMapperLocations(resolver.getResources("classpath*:mapper/*.xml"));
            return factory.getObject();
        }
    
        @Bean
        public MapperScannerConfigurer mapperScannerConfigurer() {
            MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
            mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
            mapperScannerConfigurer.setBasePackage(BASE_PACKAGE);
            //配置通用Mapper,详情请查阅官方文档
            Properties properties = new Properties();
            properties.setProperty("mappers", MAPPER_INTERFACE);
            properties.setProperty("notEmpty", "false");//insert、update是否判断字符串类型!='' 即 test="str != null"表达式内是否追加 and str != ''
            properties.setProperty("IDENTITY", "MYSQL");
            mapperScannerConfigurer.setProperties(properties);
    
            return mapperScannerConfigurer;
        }
    
    }
    

    通用基础Dao和Service编写 ,Dao路径和名称要和上面配置类指定的一致

    通用Dao

    import tk.mybatis.mapper.common.BaseMapper;
    import tk.mybatis.mapper.common.ConditionMapper;
    import tk.mybatis.mapper.common.ExampleMapper;
    import tk.mybatis.mapper.common.IdsMapper;
    import tk.mybatis.mapper.common.special.InsertListMapper;
    
    /**
     * 定制版MyBatis Mapper插件接口,如需其他接口参考官方文档自行添加。
     */
    public interface Dao<T>
            extends
            BaseMapper<T>,
            ExampleMapper<T>,
            ConditionMapper<T>,
            IdsMapper<T>,
            InsertListMapper<T> {
    }
    

    通用service

    import org.apache.ibatis.exceptions.TooManyResultsException;
    import tk.mybatis.mapper.entity.Condition;
    import tk.mybatis.mapper.entity.Example;
    import java.util.List;
    /**
     * Service 层 基础接口,其他Service 接口 请继承该接口
     */
    public interface Service<T> {
    	/**
    	 * //持久化
    	 * @param record
    	 */
        void save(T record);
        /**
         * 批量持久化
         * @param records
         */
        void save(List<T> records);
        /**
         * 批量刪除 eg:ids -> “1,2,3,4”
         * @param ids
         */
        void deleteByIds(String ids);
        /**
         * 通过主键刪除
         * @param ids
         */
        void deleteByIds(Long ...ids);
        /**
         * 更新
         * @param record
         */
        void update(T record);
        /**
         * 查询一条记录
         * @param record
         * @return
         * @throws TooManyResultsException
         */
        T selectOne(T record) throws TooManyResultsException;
        /**
         * 根据一个字段selectOne
         * @param fieldName
         * @param value
         * @return
         * @throws TooManyResultsException
         * @throws ReflectiveOperationException
         */
        T selectOneBy(String fieldName, Object value) throws TooManyResultsException,ReflectiveOperationException; //通过Model中某个成员变量名称(非数据表中column的名称)查找,value需符合unique约束
        /**
         * 根据ID查找
         * @param id
         * @return
         */
        T selectById(Long id);
        /**
         * 根据ids字符串查询eg:ids -> "1,2,3,4"
         * @param ids
         * @return
         */
        List<T> selectByIds(String ids);//通过多个ID查找//eg:ids -> “1,2,3,4”
        /**
         * 根据ids查询
         * @param ids
         * @return
         */
        List<T> selectByIds(Long ...ids);//通过多个ID查找
        /**
         * 根据条件查询 sql语句
         * Condition condition=new Condition(Test1.class);
            condition.createCriteria().andCondition("name like '%zhangsan%'");
            condition.setOrderByClause("name desc");
         * @param condition
         * @return
         */
        List<T> selectByCondition(Condition condition);//根据条件查找
        /**
         * 根据example查询
         * @param example
         * @return
         */
        List<T> selectByExample(Example example);//根据条件查找
        /**
         * 查询全部
         * @return
         */
        List<T> selectAll();//获取所有
    }
    

    通用service实现类

    import com.alibaba.fastjson.JSON;
    import com.redis.demo.common.mapper.Dao;
    import org.apache.ibatis.exceptions.TooManyResultsException;
    import org.springframework.beans.factory.annotation.Autowired;
    import tk.mybatis.mapper.entity.Condition;
    import tk.mybatis.mapper.entity.Example;
    
    import java.lang.reflect.Field;
    import java.lang.reflect.ParameterizedType;
    import java.util.List;
    
    /**
     * 基于通用MyBatis Mapper插件的Service接口的实现
     */
    public abstract class AbstractService<T> implements Service<T> {
    
        @Autowired
        protected Dao<T> mapper;
    
        private Class<T> modelClass;    // 当前泛型真实类型的Class
    
        @SuppressWarnings("unchecked")
        public AbstractService() {
            ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
            modelClass = (Class<T>) pt.getActualTypeArguments()[0];
        }
        @Override
        public void save(T record) {
            mapper.insertSelective(record);
        }
        @Override
        public void save(List<T> models) {
            mapper.insertList(models);
        }
        @Override
        public void deleteByIds(Long ...ids) {
            if (ids == null) {
    
            } else if (ids.length == 1){
                mapper.deleteByPrimaryKey(ids[0]);
            } else {
                //TODO StingUtil
    //    		mapper.deleteByIds(ids);
            }
        }
        @Override
        public void deleteByIds(String ids) {
            mapper.deleteByIds(ids);
        }
        @Override
        public void update(T model) {
            mapper.updateByPrimaryKeySelective(model);
        }
        @Override
        public T selectById(Long id) {
            return mapper.selectByPrimaryKey(id);
        }
        @Override
        public T selectOneBy(String fieldName, Object value) throws TooManyResultsException, ReflectiveOperationException {
            try {
                T model = modelClass.newInstance();
                Field field = modelClass.getDeclaredField(fieldName);
                field.setAccessible(true);
                field.set(model, value);
                return mapper.selectOne(model);
            } catch (ReflectiveOperationException e) {
                throw e;
            }
        }
        @Override
        public T selectOne(T record) throws TooManyResultsException {
            return mapper.selectOne(record);
        }
        @Override
        public List<T> selectByIds(String ids) {
            return mapper.selectByIds(ids);
        }
        @Override
        public List<T> selectByIds(Long... ids) {
            //TODO 转换数组到字符串ids
            return mapper.selectByIds(JSON.toJSONString(ids));
        }
        @Override
        public List<T> selectByCondition(Condition condition) {
            return mapper.selectByCondition(condition);
        }
        @Override
        public List<T> selectByExample(Example example) {
            return mapper.selectByExample(example);
        }
        @Override
        public List<T> selectAll() {
            return mapper.selectAll();
        }
    	}
    

    测试使用

    实体类:

    import javax.persistence.*;
    
    /**
    *@Description 用户
    *@Date 2021/1/14
    *@Version 1.0
    */
    @Table(name ="person")
    public class Person {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private  Integer id;
        @Column(name = "name")
        private String name;
        @Column(name = "age")
        private Integer age;
        @Column(name = "sex")
        private String sex;
    
    public Person() {
    }
    
    public Integer getId() {
        return id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public Integer getAge() {
        return age;
    }
    
    public void setAge(Integer age) {
        this.age = age;
    }
    
    public String getSex() {
        return sex;
    }
    
    public void setSex(String sex) {
        this.sex = sex;
    }
    
    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
    }
    

    serviceImpl实现类

    import com.redis.demo.common.service.AbstractService;
    import com.redis.demo.entity.Person;
    import org.springframework.stereotype.Service;
    
    @Service
    public class PersonServiceImpl extends AbstractService<Person> {
    }
    

    Controller接口

    import com.redis.demo.entity.Person;
    import com.redis.demo.service.PersonServiceImpl;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    import tk.mybatis.mapper.entity.Example;
    
    import javax.annotation.Resource;
    import java.util.List;
    
    /**
    *@Description 人员Person
    *@Author PengYongMei
    *@Date 2021/1/14
    *@Version 1.0
    */
    @Controller
    public class PersonController {
        private static Logger logger= LoggerFactory.getLogger(PersonController.class);
        @Resource
        private PersonServiceImpl personService;
    
    
    
    @RequestMapping(value = "/insertPerson",method = RequestMethod.GET)
    @ResponseBody
    public  void  insertPerson(){
        logger.info("保存用户——————————————————————————————————————");
        Person person = new Person();
        person.setName("藏三");
        person.setAge(26);
        person.setSex("女");
        personService.save(person);
        logger.info(person.toString());
    
    }
    
    
    @RequestMapping(value = "/getPerson",method = RequestMethod.GET)
    @ResponseBody
    public  void  getPerson(){
        logger.info("查询用户——————————————————————————————————————");
        Person person=new Person();
        person.setId(1);
        Person person1 = personService.selectOne(person);
        logger.info(person1.toString());
    
        logger.info("——————————————————————————————————————————————————————————————————————————");
    
    
        Example example=new Example(Person.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("name","藏三");
    
        List<Person> peopleList = personService.selectByExample(example);
        logger.info(peopleList.get(0).toString());
    }
    }
    

    启动类标记

    import org.mybatis.spring.annotation.MapperScan;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    @MapperScan(basePackages = "com.redis.demo.dao.*")
    public class RedisDemoApplication implements CommandLineRunner {
    
        Logger logger= LoggerFactory.getLogger(this.getClass());
    
        public static void main(String[] args) {
            SpringApplication.run(RedisDemoApplication.class, args);
        }
    
        @Override
        public void run(String... args) throws Exception {
            logger.info("Redis Project is starting");
        }
    }
    

    结果:

    调用接口
    在这里插入图片描述

    完整源码

    链接:https://pan.baidu.com/s/1lzPcTnSOHdvjt5Oj8P9ulA
    提取码:7y70

    展开全文
  • tk.mybatis错误

    2020-04-08 21:55:24
    博主,尝试了一天的tk.mybatis...org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.builder.BuilderException: Error invoking SqlProvider method (tk.mybatis.mapper.provider...

    博主,尝试了一天的tk.mybatis,最终发现了这个错误。

    
    org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.builder.BuilderException: Error invoking SqlProvider method (tk.mybatis.mapper.provider.base.BaseInsertProvider.dynamicSQL).  Cause: java.lang.InstantiationException: tk.mybatis.mapper.provider.base.BaseInsertProvider
    
    	at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:77)
    	at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:446)
    	at com.sun.proxy.$Proxy74.insert(Unknown Source)
    	at org.mybatis.spring.SqlSessionTemplate.insert(SqlSessionTemplate.java:278)
    	at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:58)
    	at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)
    	at com.sun.proxy.$Proxy108.insertSelective(Unknown Source)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.lang.reflect.Method.invoke(Method.java:498)
    	at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    	at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    	at com.sun.proxy.$Proxy109.insertSelective(Unknown Source)
    	at com.gzs.oa.dao.BaseMapperTest.test(BaseMapperTest.java:29)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.lang.reflect.Method.invoke(Method.java:498)
    	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    	at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
    	at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
    	at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    	at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    	at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    	at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    	at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
    Caused by: org.apache.ibatis.builder.BuilderException: Error invoking SqlProvider method (tk.mybatis.mapper.provider.base.BaseInsertProvider.dynamicSQL).  Cause: java.lang.InstantiationException: tk.mybatis.mapper.provider.base.BaseInsertProvider
    	at org.apache.ibatis.builder.annotation.ProviderSqlSource.createSqlSource(ProviderSqlSource.java:134)
    	at org.apache.ibatis.builder.annotation.ProviderSqlSource.getBoundSql(ProviderSqlSource.java:102)
    	at org.apache.ibatis.mapping.MappedStatement.getBoundSql(MappedStatement.java:292)
    	at org.apache.ibatis.executor.statement.BaseStatementHandler.<init>(BaseStatementHandler.java:64)
    	at org.apache.ibatis.executor.statement.PreparedStatementHandler.<init>(PreparedStatementHandler.java:40)
    	at org.apache.ibatis.executor.statement.RoutingStatementHandler.<init>(RoutingStatementHandler.java:46)
    	at org.apache.ibatis.session.Configuration.newStatementHandler(Configuration.java:558)
    	at org.apache.ibatis.executor.SimpleExecutor.doUpdate(SimpleExecutor.java:48)
    	at org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:117)
    	at org.apache.ibatis.executor.CachingExecutor.update(CachingExecutor.java:76)
    	at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:198)
    	at org.apache.ibatis.session.defaults.DefaultSqlSession.insert(DefaultSqlSession.java:185)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.lang.reflect.Method.invoke(Method.java:498)
    	at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:433)
    	... 47 more
    Caused by: java.lang.InstantiationException: tk.mybatis.mapper.provider.base.BaseInsertProvider
    	at java.lang.Class.newInstance(Class.java:427)
    	at org.apache.ibatis.builder.annotation.ProviderSqlSource.invokeProviderMethod(ProviderSqlSource.java:165)
    	at org.apache.ibatis.builder.annotation.ProviderSqlSource.createSqlSource(ProviderSqlSource.java:116)
    	... 63 more
    Caused by: java.lang.NoSuchMethodException: tk.mybatis.mapper.provider.base.BaseInsertProvider.<init>()
    	at java.lang.Class.getConstructor0(Class.java:3082)
    	at java.lang.Class.newInstance(Class.java:412)
    	... 65 more
    
    
    

    错误如上所示
    解决方法为

    package com.example.blog;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import tk.mybatis.spring.annotation.MapperScan;
    
    /**
     * @className:Test
     * @author: xxx
     * @date: 2020/4/7 20:29
     * @desc: blog启动类
     */
    
    @SpringBootApplication
    @MapperScan("com.example.blog.dao")
    public class BlogApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(BlogApplication.class, args);
        }
    
    }
    
    

    @MapperScan这个注解用的包使用tk.mybats下的就解决了,报错是一直用的是spring 的,所以tk.mybatis扫描不到.

    展开全文
  • tk.mybatis相关注解使用错误

    千次阅读 2019-05-14 16:07:46
    2019-04-11 18:38:01.201 [ERROR] c.d.d.j.e.handler.impl.DefaultJobExceptionHandler - Job 'bops.feima.task.task.OrderSycForHourJob' exception occur in job ...org.mybatis.spring.MyBatisSystemExc...

    2019-04-11 18:38:01.201 [ERROR] c.d.d.j.e.handler.impl.DefaultJobExceptionHandler - Job 'bops.feima.task.task.OrderSycForHourJob' exception occur in job processing

    org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.builder.BuilderException: Error invoking SqlProvider method (tk.mybatis.mapper.provider.base.BaseSelectProvider.dynamicSQL). Cause: java.lang.InstantiationException: tk.mybatis.mapper.provider.base.BaseSelectProvider

    at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:77)

    at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:446)

    at com.sun.proxy.$Proxy152.selectList(Unknown Source)

    at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:230)

    at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:137)

    at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:75)

    at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)

    at com.sun.proxy.$Proxy157.selectAll(Unknown Source)

    at bops.feima.task.service.impl.OrderSycServiceImpl.getMediaAccountMap(OrderSycServiceImpl.java:71)

    at bops.feima.task.service.impl.OrderSycServiceImpl.OrderSycForHour(OrderSycServiceImpl.java:195)

    at bops.feima.task.task.OrderSycForHourJob.execute(OrderSycForHourJob.java:31)

    at com.dangdang.ddframe.job.executor.type.SimpleJobExecutor.process(SimpleJobExecutor.java:41)

    at com.dangdang.ddframe.job.executor.AbstractElasticJobExecutor.process(AbstractElasticJobExecutor.java:206)

    at com.dangdang.ddframe.job.executor.AbstractElasticJobExecutor.access$000(AbstractElasticJobExecutor.java:47)

    at com.dangdang.ddframe.job.executor.AbstractElasticJobExecutor$1.run(AbstractElasticJobExecutor.java:185)

    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)

    at com.google.common.util.concurrent.TrustedListenableFutureTask$TrustedFutureInterruptibleTask.runInterruptibly(TrustedListenableFutureTask.java:117)

    at com.google.common.util.concurrent.InterruptibleTask.run(InterruptibleTask.java:38)

    at com.google.common.util.concurrent.TrustedListenableFutureTask.run(TrustedListenableFutureTask.java:77)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)

    at java.lang.Thread.run(Thread.java:748)

    Caused by: org.apache.ibatis.builder.BuilderException: Error invoking SqlProvider method (tk.mybatis.mapper.provider.base.BaseSelectProvider.dynamicSQL). Cause: java.lang.InstantiationException: tk.mybatis.mapper.provider.base.BaseSelectProvider

    at org.apache.ibatis.builder.annotation.ProviderSqlSource.createSqlSource(ProviderSqlSource.java:135)

    at org.apache.ibatis.builder.annotation.ProviderSqlSource.getBoundSql(ProviderSqlSource.java:103)

    at org.apache.ibatis.mapping.MappedStatement.getBoundSql(MappedStatement.java:292)

    at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:81)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

    at java.lang.reflect.Method.invoke(Method.java:498)

    at org.apache.ibatis.plugin.Invocation.proceed(Invocation.java:49)

    at com.github.pagehelper.SqlUtil._processPage(SqlUtil.java:402)

    at com.github.pagehelper.SqlUtil.processPage(SqlUtil.java:375)

    at com.github.pagehelper.PageHelper.intercept(PageHelper.java:252)

    at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:61)

    at com.sun.proxy.$Proxy211.query(Unknown Source)

    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148)

    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

    at java.lang.reflect.Method.invoke(Method.java:498)

    at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:433)

    ... 20 common frames omitted

    Caused by: java.lang.InstantiationException: tk.mybatis.mapper.provider.base.BaseSelectProvider

    at java.lang.Class.newInstance(Class.java:427)

    at org.apache.ibatis.builder.annotation.ProviderSqlSource.createSqlSource(ProviderSqlSource.java:117)

    ... 40 common frames omitted

    Caused by: java.lang.NoSuchMethodException: tk.mybatis.mapper.provider.base.BaseSelectProvider.<init>()

    at java.lang.Class.getConstructor0(Class.java:3082)

    at java.lang.Class.newInstance(Class.java:412)

    ... 41 common frames omitted

    2019-04-11 18:38:01.201 [ERROR] c.d.d.j.e.handler.impl.DefaultJobExceptionHandler - Job 'bops.feima.task.task.OrderSycForHourJob' exception occur in job processing

    org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.builder.BuilderException: Error invoking SqlProvider method (tk.mybatis.mapper.provider.base.BaseSelectProvider.dynamicSQL). Cause: java.lang.InstantiationException: tk.mybatis.mapper.provider.base.BaseSelectProvider

    at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:77)

    at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:446)

    at com.sun.proxy.$Proxy152.selectList(Unknown Source)

    at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:230)

    at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:137)

    at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:75)

    at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)

    at com.sun.proxy.$Proxy157.selectAll(Unknown Source)

    at bops.feima.task.service.impl.OrderSycServiceImpl.getMediaAccountMap(OrderSycServiceImpl.java:71)

    at bops.feima.task.service.impl.OrderSycServiceImpl.OrderSycForHour(OrderSycServiceImpl.java:195)

    at bops.feima.task.task.OrderSycForHourJob.execute(OrderSycForHourJob.java:31)

    at com.dangdang.ddframe.job.executor.type.SimpleJobExecutor.process(SimpleJobExecutor.java:41)

    at com.dangdang.ddframe.job.executor.AbstractElasticJobExecutor.process(AbstractElasticJobExecutor.java:206)

    at com.dangdang.ddframe.job.executor.AbstractElasticJobExecutor.access$000(AbstractElasticJobExecutor.java:47)

    at com.dangdang.ddframe.job.executor.AbstractElasticJobExecutor$1.run(AbstractElasticJobExecutor.java:185)

    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)

    at com.google.common.util.concurrent.TrustedListenableFutureTask$TrustedFutureInterruptibleTask.runInterruptibly(TrustedListenableFutureTask.java:117)

    at com.google.common.util.concurrent.InterruptibleTask.run(InterruptibleTask.java:38)

    at com.google.common.util.concurrent.TrustedListenableFutureTask.run(TrustedListenableFutureTask.java:77)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)

    at java.lang.Thread.run(Thread.java:748)

    Caused by: org.apache.ibatis.builder.BuilderException: Error invoking SqlProvider method (tk.mybatis.mapper.provider.base.BaseSelectProvider.dynamicSQL). Cause: java.lang.InstantiationException: tk.mybatis.mapper.provider.base.BaseSelectProvider

    at org.apache.ibatis.builder.annotation.ProviderSqlSource.createSqlSource(ProviderSqlSource.java:135)

    at org.apache.ibatis.builder.annotation.ProviderSqlSource.getBoundSql(ProviderSqlSource.java:103)

    at org.apache.ibatis.mapping.MappedStatement.getBoundSql(MappedStatement.java:292)

    at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:81)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

    at java.lang.reflect.Method.invoke(Method.java:498)

    at org.apache.ibatis.plugin.Invocation.proceed(Invocation.java:49)

    at com.github.pagehelper.SqlUtil._processPage(SqlUtil.java:402)

    at com.github.pagehelper.SqlUtil.processPage(SqlUtil.java:375)

    at com.github.pagehelper.PageHelper.intercept(PageHelper.java:252)

    at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:61)

    at com.sun.proxy.$Proxy211.query(Unknown Source)

    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148)

    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

    at java.lang.reflect.Method.invoke(Method.java:498)

    at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:433)

    ... 20 common frames omitted

    Caused by: java.lang.InstantiationException: tk.mybatis.mapper.provider.base.BaseSelectProvider

    at java.lang.Class.newInstance(Class.java:427)

    at org.apache.ibatis.builder.annotation.ProviderSqlSource.createSqlSource(ProviderSqlSource.java:117)

    ... 40 common frames omitted

    Caused by: java.lang.NoSuchMethodException: tk.mybatis.mapper.provider.base.BaseSelectProvider.<init>()

    at java.lang.Class.getConstructor0(Class.java:3082)

    at java.lang.Class.newInstance(Class.java:412)

    ... 41 common frames omitted

    2019-04-11 18:38:01.201 [ERROR] c.d.d.j.e.handler.impl.DefaultJobExceptionHandler - Job 'bops.feima.task.task.OrderSycForHourJob' exception occur in job processing

    org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.builder.BuilderException: Error invoking SqlProvider method (tk.mybatis.mapper.provider.base.BaseSelectProvider.dynamicSQL). Cause: java.lang.InstantiationException: tk.mybatis.mapper.provider.base.BaseSelectProvider

    at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:77)

    at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:446)

    at com.sun.proxy.$Proxy152.selectList(Unknown Source)

    at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:230)

    at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:137)

    at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:75)

    at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)

    at com.sun.proxy.$Proxy157.selectAll(Unknown Source)

    at bops.feima.task.service.impl.OrderSycServiceImpl.getMediaAccountMap(OrderSycServiceImpl.java:71)

    at bops.feima.task.service.impl.OrderSycServiceImpl.OrderSycForHour(OrderSycServiceImpl.java:195)

    at bops.feima.task.task.OrderSycForHourJob.execute(OrderSycForHourJob.java:31)

    at com.dangdang.ddframe.job.executor.type.SimpleJobExecutor.process(SimpleJobExecutor.java:41)

    at com.dangdang.ddframe.job.executor.AbstractElasticJobExecutor.process(AbstractElasticJobExecutor.java:206)

    at com.dangdang.ddframe.job.executor.AbstractElasticJobExecutor.access$000(AbstractElasticJobExecutor.java:47)

    at com.dangdang.ddframe.job.executor.AbstractElasticJobExecutor$1.run(AbstractElasticJobExecutor.java:185)

    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)

    at com.google.common.util.concurrent.TrustedListenableFutureTask$TrustedFutureInterruptibleTask.runInterruptibly(TrustedListenableFutureTask.java:117)

    at com.google.common.util.concurrent.InterruptibleTask.run(InterruptibleTask.java:38)

    at com.google.common.util.concurrent.TrustedListenableFutureTask.run(TrustedListenableFutureTask.java:77)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)

    at java.lang.Thread.run(Thread.java:748)

    Caused by: org.apache.ibatis.builder.BuilderException: Error invoking SqlProvider method (tk.mybatis.mapper.provider.base.BaseSelectProvider.dynamicSQL). Cause: java.lang.InstantiationException: tk.mybatis.mapper.provider.base.BaseSelectProvider

    at org.apache.ibatis.builder.annotation.ProviderSqlSource.createSqlSource(ProviderSqlSource.java:135)

    at org.apache.ibatis.builder.annotation.ProviderSqlSource.getBoundSql(ProviderSqlSource.java:103)

    at org.apache.ibatis.mapping.MappedStatement.getBoundSql(MappedStatement.java:292)

    at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:81)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

    at java.lang.reflect.Method.invoke(Method.java:498)

    at org.apache.ibatis.plugin.Invocation.proceed(Invocation.java:49)

    at com.github.pagehelper.SqlUtil._processPage(SqlUtil.java:402)

    at com.github.pagehelper.SqlUtil.processPage(SqlUtil.java:375)

    at com.github.pagehelper.PageHelper.intercept(PageHelper.java:252)

    at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:61)

    at com.sun.proxy.$Proxy211.query(Unknown Source)

    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148)

    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

    at java.lang.reflect.Method.invoke(Method.java:498)

    at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:433)

    ... 20 common frames omitted

    Caused by: java.lang.InstantiationException: tk.mybatis.mapper.provider.base.BaseSelectProvider

    at java.lang.Class.newInstance(Class.java:427)

    at org.apache.ibatis.builder.annotation.ProviderSqlSource.createSqlSource(ProviderSqlSource.java:117)

    ... 40 common frames omitted

    Caused by: java.lang.NoSuchMethodException: tk.mybatis.mapper.provider.base.BaseSelectProvider.<init>()

    at java.lang.Class.getConstructor0(Class.java:3082)

    at java.lang.Class.newInstance(Class.java:412)

    ... 41 common frames omitted

    2019-04-11 18:38:12.672 [INFO ] com.netflix.config.ChainedDynamicProperty - Flipping property: bops-time-task.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647

     

    问题:启动类的@MapperScan(basePackages = "xxx.xxx.xxx.mapper") 注解导包错误

     

    解决:

    把import org.mybatis.spring.annotation.MapperScan;

    换成import tk.mybatis.spring.annotation.MapperScan;

     

    展开全文
  • springboot项目,引用了tk.mybatis,mapper继承了通用的extends BaseMapper,但是没有ByExample这些,不知道是哪出错了。![图片说明](https://img-ask.csdn.net/upload/202005/20/1589967714_841672.png) ``` ...
  • DM8+SpringBoot+HiKari+...tk.MyBatis+PageHelper</a></p> 数据迁移+数据同步DMHS方案,在达梦、Oracle、Mysql(canal基于binlog日志)上异曲同工之处?</p>
  • 通过When Case批量更新 ...-- tk.mybatis --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.1.5</ver

    通过When Case批量更新

    1、pom

            <!-- tk.mybatis -->
            <dependency>
                <groupId>tk.mybatis</groupId>
                <artifactId>mapper-spring-boot-starter</artifactId>
                <version>2.1.5</version>
            </dependency>

     2、注解接口 -> MyDuplicateSelectiveMapper.java

    package com.sundear.base.mybatis.tk.base;
    
    import com.sundear.base.mybatis.tk.provider.MyDuplicateSelectiveProvider;
    import org.apache.ibatis.annotations.InsertProvider;
    import tk.mybatis.mapper.annotation.RegisterMapper;
    
    import java.util.List;
    
    /**
     * @Author: xiu
     * @Date: 2021/5/8 17:43
     * @description 自定义,InsertListSelective
     */
    @RegisterMapper
    public interface MyDuplicateSelectiveMapper<T> {
    
        /**
         * 以var1第一条数据字段是否为空 进行Selective处理
         *
         * @param var1 list
         * @return
         */
        @InsertProvider(
                type = MyDuplicateSelectiveProvider.class,
                method = "dynamicSQL"
        )
        int myDuplicateSelective(List<? extends T> var1);
    }

    3、MyDuplicateSelectiveProvider.java

    package com.sundear.base.mybatis.tk.provider;
    
    import org.apache.ibatis.mapping.MappedStatement;
    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.Iterator;
    import java.util.Set;
    
    /**
     * @Author: xiu
     * @Date: 2021/5/8 17:46
     * @description
     */
    public class MyDuplicateSelectiveProvider extends MapperTemplate {
    
        public MyDuplicateSelectiveProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
            super(mapperClass, mapperHelper);
        }
    
        public String myDuplicateSelective(MappedStatement ms) {
            StringBuilder sql = myInsertListSelective(ms);
            sql.append(" ON DUPLICATE KEY UPDATE ");
            sql.append(" <trim suffixOverrides=\",\"> ");
    
            Class<?> entityClass = this.getEntityClass(ms);
            Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
            columnSet.forEach((tempColumn) -> {
                if (!tempColumn.isId()) {
                    sql.append("<if test=\"null != list[0].");
                    sql.append(tempColumn.getEntityField().getName());
                    sql.append("\">");
                    sql.append(tempColumn.getColumn() );
                    sql.append(" = values(" );
                    sql.append(tempColumn.getColumn() );
                    sql.append("),</if>");
                }
            });
            sql.append("</trim>");
            return sql.toString();
        }
    
        private StringBuilder myInsertListSelective(MappedStatement ms) {
            Class<?> entityClass = this.getEntityClass(ms);
            StringBuilder sql = new StringBuilder();
            EntityColumn logicDeleteColumn = SqlHelper.getLogicDeleteColumn(entityClass);
            sql.append("<bind name=\"listNotEmptyCheck\" value=\"@tk.mybatis.mapper.util.OGNL@notEmptyCollectionCheck(list, '" + ms.getId() + " 方法参数为空')\"/>");
            sql.append(SqlHelper.insertIntoTable(entityClass, this.tableName(entityClass), "list[0]"));
            sql.append(insertColumns(entityClass, false, true, false, "list[0]", logicDeleteColumn));
            sql.append(" VALUES ");
            sql.append("<foreach collection=\"list\" item=\"record\" separator=\",\" >");
            sql.append("<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">");
            Set<EntityColumn> columnList = EntityHelper.getColumns(entityClass);
    
            Iterator var6 = columnList.iterator();
            EntityColumn column;
            while (true) {
                while (true) {
                    do {
                        if (!var6.hasNext()) {
                            sql.append("</trim>");
                            sql.append("</foreach>");
                            return sql;
                        }
    
                        column = (EntityColumn) var6.next();
                    } while (!column.isInsertable());
    
                    if (logicDeleteColumn != null && logicDeleteColumn == column) {
                        sql.append(SqlHelper.getLogicDeletedValue(column, false)).append(",");
                    } else {
                        if (column.isIdentity()) {
                            sql.append(SqlHelper.getIfCacheNotNull(column, column.getColumnHolder((String) null, "_cache", ",")));
                        } else {
                            sql.append(SqlHelper.getIfNotNull("list[0]", column, column.getColumnHolder("record", (String) null, ","), this.isNotEmpty()));
                        }
    
                        if (column.isIdentity()) {
                            sql.append(SqlHelper.getIfCacheIsNull(column, column.getColumnHolder() + ","));
                        }
                    }
                }
            }
    
        }
    
        private String insertColumns(Class<?> entityClass, boolean skipId, boolean notNull, boolean notEmpty, String entityName, EntityColumn logicDeleteColumn) {
            StringBuilder sql = new StringBuilder();
            sql.append("<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">");
            Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
            Iterator var6 = columnSet.iterator();
    
            while (true) {
                EntityColumn column;
                do {
                    do {
                        if (!var6.hasNext()) {
                            sql.append("</trim>");
                            return sql.toString();
                        }
    
                        column = (EntityColumn) var6.next();
                    } while (!column.isInsertable());
                } while (skipId && column.isId());
    
                if (logicDeleteColumn != null && logicDeleteColumn == column) {
                    sql.append(column.getColumn()).append(",");
                } else {
                    if (notNull) {
                        sql.append(SqlHelper.getIfNotNull(entityName, column, column.getColumn() + ",", notEmpty));
                    } else {
                        sql.append(column.getColumn() + ",");
                    }
                }
            }
        }
    }
    

    3、用我们的基础mapper继承我们上述接口 -》上篇文章已经创建过这个类

    package com.sundear.base.mybatis;
    
    import com.sundear.base.mybatis.tk.base.MyDuplicateSelectiveMapper;
    import com.sundear.base.mybatis.tk.base.MyUpdateListForeachMapper;
    import com.sundear.base.mybatis.tk.base.MyUpdateListWhenCaseMapper;
    
    /**
     * @Author: 秀丽
     * @Date: 2021/5/8 17:41
     * @description 继承自定义的方法
     */
    public interface MyBaseMapper<T> extends
            MyUpdateListForeachMapper<T>,
            MyUpdateListWhenCaseMapper<T>,
            MyDuplicateSelectiveMapper<T> {
    
    }

    4、然后我们就可以用实体类的mapper直接调用  myUpdateListWhenCaseByPrimaryKey(List<T> var1)  方法去批量更新了list了

    @Slf4j
    @SpringBootTest
    @RunWith(SpringRunner.class)
    public class RunTest {
    
        @Resource
        private TbTestMapper tbTestMapper;
    
        @Test
        public void test2() {
            List<TbTest> list = new ArrayList<>();
            for (int i = 0; i < 4; i++) {
                list.add(TbTest.builder().value(""+i).id(IdWorker.getIdWorker().nextIdStr()).build());
            }
            //方式一 foreach
            tbTestMapper.myUpdateListForeachByPrimaryKey(list);
    
            //方式二 when case
            Example example = new Example(TbTest.class);
            example.createCriteria()
                    .andIn(TbTest.Fields.id,list.stream().map(TbTest::getId).collect(Collectors.toList()));
            tbTestMapper.myUpdateListWhenCaseByPrimaryKey(list,example);
    
            //方式三 Duplicate
            tbTestMapper.myDuplicateSelective(list);
        }
    
    }

    5、三种方法效率

    方式三效率最高,其次方式一

    方式二为了满足通用调用方式。而且条件when是id。在大数据量下循环次数比较多,所以效率不如方式一。。可以自行测试。

    方式三既可以满足update list的业务要求,也可以满足insert list的业务需求。还是比较方便的。

    6、如有bug,请留言,谢谢。

    展开全文
  • IDEA:无法获取实体类xxx对应的表名!问题描述报错详情解决办法(1)使用的是@MapperScan注解(2)devtools热部署问题 问题描述 ... at tk.mybatis.mapper.mapperhelper.EntityHelper.getEntityTable(Entit
  • 搭建好eclipse版的ssm+maven+tk.mybatis+redis集成的demo。新手快速上手直接demo。完整高质量。整理不少时间分享没人赞好心疼吖吖。。。 或者直接看下面地址博客(由于太长所以博客不全) ...
  • Cause: java.lang.NoSuchMethodException: tk.mybatis.mapper.provider.base.BaseSelectProvider.<init>() at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible...
  • TK.mybatis使用详情

    2021-11-09 16:06:46
    TkMybatis 什么是TKMybatisTKMybatis是基于 Mybatis 框架开发的一个工具,内部实现了对单表的基本数据操作,只需要简单继承 TKMybatis 提供的接口,就能够实现无需编写任何 sql 即能完成单表操作 基本步骤 ...
  • 通用Mapper是一款针对mybatis进行扩展的轻量级组件,使用起来非常方便。当调用其针对mysql进行批量添加数据的方法时,发现报错,仔细研究了一番,发现是在使用通用Mapper上出现了问题。下面贴出本文使用的通用的...
  • 主要介绍了Spring Boot整合tk.mybatis代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
  • tk.mybatis.mapper.common.Mapper的样例使用
  • 使用mybatis配合tk.mybatis进行数据库操作 这是一个spring cloud工程mybatis使用tk.myabtis通用mapper的总结博客 使用tk.mybatis非常简单,但是有一些坑,现在先说引入mybatis,也非常简单 ...org.mybatis.spring.b
  • 最近做项目投产的时候发现一个...tk.mybatis.mapper.mapperhelper.EntityHelper.getEntityTable(EntityHelper.java:69) ~[mapper-core-1.1.5.jar:na] at tk.mybatis.mapper.entity.Example.<init>(Example.java:
  • 不过最近看到公司项目中有使用tk.mybatis的,和mybatis-plus是有异曲同工之妙的,所有小编带大家配置和使用一下常用方法来体验一下!! 二、配置信息 首先我们先把pom文件的依赖导入进来: <dependencies> <...
  • SpringBoot使用tk.mybatis整合Mybatis

    千次阅读 2020-04-19 19:37:48
    SpringBoot使用tk.mybatis整合Mybatis pom.xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot...
  • 通过When Case批量更新 ...-- tk.mybatis --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.1.5</ver
  • java.lang.RuntimeException: Cannot instantiate object of type tk.mybatis.generator.MapperPlugin at org.mybatis.generator.internal.ObjectFactory.createInternalObject(ObjectFactory.java:182) at org.my
  • -- tk.mybatis --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.1.5</versi
  • tk.mybatis初探

    2019-10-09 15:03:26
    据说tk.mybatis能够让我不写sql代码就可以所有单表操作问题,作为热爱偷懒的我,怎么能放过这种机会。talk is cheap, show me the code。赶紧搞个例子爽一把先。 例子使用springboot与MySQL搭建,因此需要准备必要...
  • tk.mybatis源码

    千次阅读 2018-07-18 16:46:33
    import tk.mybatis.mapper.common.Mapper; import tk.mybatis.mapper.common.MySqlMapper; public interface BaseMapper&amp;lt;T&amp;gt; extends Mapper&amp;lt;T&amp;gt;, MySqlMapper&amp;...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 12,799
精华内容 5,119
关键字:

tk.mybatis