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
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.