search
HomeJavajavaTutorialHow to integrate tkMapper with SpringBoot

How to integrate tkMapper with SpringBoot

May 12, 2023 pm 12:58 PM
springboottkmapper

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)

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--lombok省略代码-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- h3嵌入式数据-->
        <dependency>
            <groupId>com.h3database</groupId>
            <artifactId>h3</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- tk-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>3.4.5</version>
        </dependency>

    </dependencies>

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 &#39;主键ID&#39;,
    name VARCHAR(30) NULL DEFAULT NULL COMMENT &#39;姓名&#39;,
    age INT(11) NULL DEFAULT NULL COMMENT &#39;年龄&#39;,
    email VARCHAR(50) NULL DEFAULT NULL COMMENT &#39;邮箱&#39;,
    PRIMARY KEY (id)
);

data-h3.sql

DELETE FROM user;

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

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<T> extends Mapper<T> ,MySqlMapper<T> {
}

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<User> {
}

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<User> 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:亿速云. If there is any infringement, please contact admin@php.cn delete
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.