Home  >  Article  >  Java  >  How to integrate tkMapper with SpringBoot

How to integrate tkMapper with SpringBoot

王林
王林forward
2023-05-12 12:58:061090browse

SpringBoot integrates tkMapper

1 To build a SpringBoot project, there are a lot of online tutorials on how to build it. I won’t describe it here and go straight to the topic. First, let’s take a look at the overall project structure

How to integrate tkMapper with SpringBoot

2 Pom file introduces dependencies (note dependency conflicts)


        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
        
            org.projectlombok
            lombok
            true
        
        
        
            com.h3database
            h3
            runtime
        
        
        
            tk.mybatis
            mapper-spring-boot-starter
            RELEASE
        
        
            tk.mybatis
            mapper
            3.4.5
        

    

3 Create a new db folder in the resources directory , used to store data files, where schema-h3.sql is the database Schema script, data-h3.sql is the Data script

schema-h3.sql

DROP TABLE IF EXISTS user;

CREATE TABLE user
(
    id BIGINT(20) NOT NULL COMMENT '主键ID',
    name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
    age INT(11) NULL DEFAULT NULL COMMENT '年龄',
    email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
    PRIMARY KEY (id)
);

data-h3.sql

DELETE FROM user;

INSERT INTO user (id, name, age, email) VALUES
(1, 'red', 18, 'test1@tian.com'),
(2, 'yll', 20, 'test2@tian.com'),
(3, 'putty', 22, 'test3@tian.com'),
(4, 'ele', 24, 'test4@tian.com'),
(5, 'tom', 26, 'test5@tian.com');

4 application.yml

spring:
  datasource:
    driver-class-name: org.h3.Driver
    schema: classpath:db/schema-h3.sql
    data: classpath:db/data-h3.sql
    url: jdbc:h3:mem:root
    username: root
    password: root

5 Create a new one under the generated project path tk package, create a new bean package (to store entity classes), a dao package (to store Mapper interface classes), and a config package (to store configuration classes) under the tk package

Create a new general Mapper under the tk package Interface MyMapper

Inherits Mapper and MySqlMapper. In the future, our business dao can directly integrate MyMapper

This interface cannot be scanned, otherwise it will Error

MyMapper.java

package com.tian.tkmapper;

import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

@Repository
public interface MyMapper extends Mapper ,MySqlMapper {
}

Create a new User class under the bean package. Lombok omits the code here, and the @Data annotation contains get/ set and other methods

User.java

package com.tian.tkmapper.tk.bean;

import lombok.Data;

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

Create a new business interface UserDao under the dao package

UserDao.java

package com.tian.tkmapper.tk.dao;

import com.tian.tkmapper.MyMapper;
import com.tian.tkmapper.tk.bean.User;
import org.springframework.stereotype.Repository;

@Repository
public interface UserDao extends MyMapper {
}

New configuration class MybatisConfigurer

MybatisConfigurer.java

package com.tian.tkmapper.tk.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Properties;

@Configuration
public class MybatisConfigurer {
    @Resource
    private DataSource dataSource;

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage("com.tian.tkmapper.tk.bean");

        //添加XML目录
//        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//        bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        return bean.getObject();
    }

    @Configuration
    @AutoConfigureAfter(MybatisConfigurer.class)
    public static class MyBatisMapperScannerConfigurer {

        @Bean
        public MapperScannerConfigurer mapperScannerConfigurer() {
            MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
            mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
            mapperScannerConfigurer.setBasePackage("com.tian.tkmapper.tk.dao.*");
            //配置通用mappers
            Properties properties = new Properties();
            properties.setProperty("mappers", "com.tian.tkmapper.MyMapper");
            properties.setProperty("notEmpty", "false");
            properties.setProperty("IDENTITY", "MYSQL");
            mapperScannerConfigurer.setProperties(properties);
            return mapperScannerConfigurer;
        }
    }
   }

6 Add @MapperScan in the startup class

package com.tian.tkmapper;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@MapperScan(basePackages = "com.tian.tkmapper.tk.dao")//mapper接口的路径
public class TkmapperApplication {

    public static void main(String[] args) {
        SpringApplication.run(TkmapperApplication.class, args);
    }
}

7 Test the code for testing

package com.tian.tkmapper;

import com.tian.tkmapper.tk.bean.User;
import com.tian.tkmapper.tk.dao.UserDao;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TkmapperApplicationTests {
    @Autowired
    private UserDao userDao;

    @Test
    public void testSelect() {
        System.out.println(("----- selectAll method test ------"));
        List userList = userDao.selectAll();
        Assert.assertEquals(5, userList.size());
        userList.forEach(System.out::println);
    }
   }

Finally, when you see the following output, it is successful

How to integrate tkMapper with SpringBoot

8 The pitfalls encountered

    a> MyMapper不能被扫描到,解决方案很多,不让启动类启动时扫描到就可以
    b> 启动类中@MapperScan要引tk包下面的 import tk.mybatis.spring.annotation.MapperScan;
    c>pom文件依赖冲突

The above is the detailed content of How to integrate tkMapper with SpringBoot. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete