search
HomeJavajavaTutorialWhat are the problems that may be encountered when SpringBoot integrates MyBatis?

Try not to use the unit test provided by jUnit

As a request, try to use the test class provided by SpringBoot for testing, which can automatically scan components and use bean objects in the container

And if If there is an injected object in a component, then this component must be taken out from the SpringBoot container and then the functions of the injected object can be used! ! !

There was an error today and it took me a long time to solve it. Finally, I found out that it was a very low-level and basic error!

This is the mapper interface. Using @mapper is equivalent to registering the proxy object of the interface into the bean, but it cannot be found in the context (actually it is normal)

Because the @Mapper annotation is Mybatis provided, and the @Autowried annotation is provided by Spring. IDEA can understand the context of Spring, but it is not related to Mybatis. And we can see from the @Autowried source code that by default, @Autowried requires that dependent objects must exist, so IDEA can only give a red warning at this time.

package com.bit.mapper;
import com.bit.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface UserMapper {
    User selectById(@Param("userid") Integer id);
}

This is the xml file corresponding to the mapper interface, and there is no problem.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bit.mapper.UserMapper">
        <select id="selectById" resultType="com.bit.pojo.User">
            select * from users where id = #{userid}
        </select>
</mapper>

Add the xml file in the java directory to the resource resource, and nest it in the build tag. There is also no problem.

<resources>    
    <resource>        
        <directory>src/main/java</directory>        
        <includes>            
            <include>**/*.xml</include>        
        </includes>    
    </resource>
</resources>

Then we wrote the service layer, wrote a UserService interface, and created an implementation class of the UserServiceImpl interface

In this implementation class, when injecting UserMapper, it kept saying that it could not be injected. I always thought that there was Problem (but in the end I found that there was no problem)

What are the problems that may be encountered when SpringBoot integrates MyBatis?

I finished writing the service implementation class, and there was no problem

package com.bit.service;
import com.bit.mapper.UserMapper;
import com.bit.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Override
    public User queryById(Integer id) {
        System.out.println("进入了service");
        return userMapper.selectById(id);
    }
}

Then I went to test it directly, I tested it Woolen cloth?

Instantiate UserService, create a new object, and then call the method directly to see if UserMapper can be called to query the database. Then I kept getting null pointer exception errors

@SpringBootTest
class BitApplicationTests {
    @Test
    void contextLoads() {
        UserService userService = new UserServiceImpl();
        userService.queryById(13);
        System.out.println(userService);
        System.out.println(userService.queryById(15));
        System.out.println(userService.queryById(13));
    }
}

What are the problems that may be encountered when SpringBoot integrates MyBatis?

  I once thought that the mapper interface was not injected into UserServcie, which caused the method of calling UserServcie to be called UserMapper The method is empty, I thought it was a problem with the Mapper interface. I searched various ways how to solve it. After a few hours, I found the answer in other people's blogs

  Our UserMapper is injected into UserServiceImpl, We cannot use UserServcieIml directly. If we use its function in other classes, we must inject this class into the current class and get the UserService from the container before we can call it correctly without a null pointer exception. I always Not found, this is a very low-level error.

Correct approach: First assemble it into the current object, and then get the bean from the container for use

@SpringBootTest
class BitApplicationTests {
    @Autowired
    private UserService userService;
    @Test
    void contextLoads() {
        System.out.println(userService.queryById(15));
        System.out.println(userService.queryById(13));
    }
}

The above is the detailed content of What are the problems that may be encountered when SpringBoot integrates MyBatis?. 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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.