2021 SpringBoot integration MyBatis summary


Preface:
If you don't have a database yet, then you need to install a database first, whether it is a local or a virtual machine or a server, you need to have a database as a basis. Provide a detailed tutorial on how to install mysql database under linux. My girlfriend will read it: mysql database is installed in linux environment
, and a SpringBoot project has been established by default here. If you don’t know how to quickly build a SpringBoot project, you can see Next article: Quickly build a Jsp+SpringBoot project .

1. Integration process

SpringBoot integrates MyBatis mainly in the following steps: import related dependencies, configure application.properties file, create service interface and its implementation class, create dao interface, create mapper file according to the method content in dao interface, and follow each step according to this process Give details.

1. Import related dependencies

The dependencies that need to be imported here include MyBatis dependency package, mysql database driver package, and data source connection pool dependency package, as follows:
Version introduction:
SpringBoot: 2.4.4
mybatis-spring-boot-starter: 2.1.2
mysql -connector-java: 5.1.38
druid: 1.1.19

	<!--引入mybatis的依赖-->
	<dependency>
	   <groupId>org.mybatis.spring.boot</groupId>
	   <artifactId>mybatis-spring-boot-starter</artifactId>
	   <version>2.1.2</version>
	</dependency>
	
	<!--引入连接mysql的驱动-->
	<dependency>
	   <groupId>mysql</groupId>
	   <artifactId>mysql-connector-java</artifactId>
	   <version>5.1.38</version>
	</dependency>
	
	<!--引入数据源连接池依赖-->
	<dependency>
	   <groupId>com.alibaba</groupId>
	   <artifactId>druid</artifactId>
	   <version>1.1.19</version>
	</dependency>

2. Configuration file application.properties

The parameters that need to be configured here are database and mybatis. The details are as follows. Note that we don't need to provide configuration parameters for other databases. SpringBoot will have a default configuration.

# 数据库相关配置
#连接池
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#驱动类
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#数据库地址
spring.datasource.url=jdbc:mysql://192.168.150.130:3306/shiro?characterEncoding=UTF-8&useSSL=false
#数据库用户名与密码
spring.datasource.username=root
spring.datasource.password=super

# mybatis 别名配置,配置该参数mapper中才认识自定义类型
mybatis.type-aliases-package=com.example.demo5.entry
# 包扫描,配置了该参数MyBatis才能找到我们写mapper文件
mybatis.mapper-locations=classpath:com/example/demo5/mapper/*.xml

3. Create service interface and its implementation class, create dao interface

There is nothing to say about this, that is, the ordinary interface is created, then the class is implemented and then the dao interface is called. The code is as follows:

  1. servic interface

    public interface ShiroUserService {
          
          
        void insertUser(ShiroUser shiroUser);
        ShiroUser queryUser(String username);
    }
    
  2. service interface implementation class

    @Service
    @Transactional
    public class ShiroUserServiceImpl implements ShiroUserService {
          
          
    
       @Resource
       private ShiroUserDao shiroUserDao;
    
       @Override
       public void insertUser(ShiroUser shiroUser) {
          
          
           //使用MD5+盐+hash散列进行对密码加密
           String salt = SaltUttil.getSalt(10);
           Md5Hash md5Hash = new Md5Hash(shiroUser.getPassword(),salt ,2048);
           shiroUser.setPassword(md5Hash.toString());
           shiroUser.setSalt(salt);
           shiroUserDao.insertUser(shiroUser);
       }
    
       @Override
       public ShiroUser queryUser(String username) {
          
          
           ShiroUser shiroUser = shiroUserDao.queryUser(username);
           return shiroUser;
       }
    }
    
  3. dao interface creation

    public interface ShiroUserDao {
          
          
        void insertUser(ShiroUser shiroUser);
        ShiroUser queryUser(String username);
    }
    

    It should be noted that the mapper annotation can be used here, or the mapperScan annotation can be added to the startup class. Both of these annotations can map the dao and mapper files together. It is recommended to add the MapperScan annotation to the startup class to pass in the package path that needs to be scanned. That's it, as follows:

    @MapperScan(value = "com.example.demo5.dao")
    @SpringBootApplication
    public class Demo5Application {
          
          
        public static void main(String[] args) {
          
          
            SpringApplication.run(Demo5Application.class, args);
        }
    }
    

4. Create a mapper file based on dao

First, you need to create a folder under the resource folder to store the mapper.xml file. The path of the folder is the path we configured in appliction.properties. In fact, it should be created first and then configured. This is written here to configure Write together

  1. There is
    no requirement to create a mapper folder . The path does not need to be consistent with dao or whoever. It is worth noting that slashes must be used to create multi-level file directories. Do not use dots. The dots create a single-level directory structure. I have stepped on it because of this. I am deeply impressed after going through the pit.
    Insert picture description here

  2. Create mapper.xml file

    <?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.example.demo5.dao.ShiroUserDao">
    
        <sql id="shiro_user_fields">
          oid,username,password,salt
        </sql>
    
        <insert id="insertUser" parameterType="ShiroUser" useGeneratedKeys="true" keyProperty="oid">
            insert into shiro_user values (#{
          
          oid},#{
          
          username},#{
          
          password},#{
          
          salt})
        </insert>
    
        <select id="queryUser" parameterType="java.lang.String" resultType="ShiroUser">
            select
            <include refid="shiro_user_fields"/>
            from shiro_user where 1=1
            <if test="username != null and username != ''">
              and username = #{
          
          username}
            </if>
        </select>
    </mapper>
    

    This is also a standard mapper file, which can be used as a template. The meaning of each sentence in the specific mapper file is not explained one by one. This article aims to summarize the process.

5. Complete the integration

In fact, the integration of SpringBoot+MyBatis is now complete. The non-main process of creating entity classes and creating controller interfaces is not written. It is not a complicated thing at first, but this is not the only integration method, but this integration method is faster, and the fast root lies in the use of the Mybatis launcher provided by SpringBoot, which saves a lot of xml configuration. But no matter how simple things are, there may be various problems. The following lists a variety of problems that may arise during the integration process, and give answers, make a summary by yourself, and hope that it will also help readers passing by.

2. Summary of the problem

This process will inevitably encounter many problems. For those who have been in contact with this architecture for a long time, it may be obvious at a glance that for those who are new to it, various bd may be needed. Here are a few common problems listed one by one.

1. Use Mapper annotation on dao?

In the above integration process, there is no annotation on the dao, but in fact, we can add a Mapper annotation to each dao file, which can associate the dao with the mapper.xml file, and automatically generate an implementation class for the dao and inject it Into the spring container. However, adding the MapperScan annotation to the startup class has the same effect as the annotation.

2.报错SSL connection without server’s identity verification is not recommended

Insert picture description here
This is caused by the inability to verify the security of the server where the database is located. We can let Spring not check the value and add useSSL=false to the database path configuration.

spring.datasource.url=jdbc:mysql://192.168.150.130:3306/shiro?characterEncoding=UTF-8&useSSL=false

This is solved.

3.BindingException binding exception

This is because IDEA does not compile xml files by default. We need to add the following content under the build level of the pom file to tell us to compile our xml files together when compiling the project:

		<resources>
            <resource>
                <directory>src/main/Java</directory>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.* </include>
                </includes>
            </resource>
        </resources>

4. If a database connection error is reported

This error has been encountered by the author but has not been restored. The configuration parameters of the database are all normal. The database is also normal. But it can't be connected. At this time, other connection parameters of the database are added and it is normal. But it has not been restored, as a reference.

spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5

5. If the primary key problem is reported

The error is reported, or the two parameters are not configured in the insert statement in the mapper file, use the automatically generated primary key, and the second is the name of the database primary key. If both are configured, check whether the table in the database is configured to support The primary key is incremented.

useGeneratedKeys="true" keyProperty="oid"

Insert picture description here

6. The problem of garbled data storage

Add characherEncoding=UTF-8 when configuring the database address in application.properties, as follows:

spring.datasource.url=jdbc:mysql://192.168.150.130:3306/shiro?characterEncoding=UTF-8&useSSL=false

In addition, check whether the database was created in UTF-8.
Insert picture description here
If all of these are normal, there may be garbled characters in the front-end and back-end interactions. Pay attention to whether the encoding of the front-end files is normal, such as whether the encoding of jsp, html, etc. is wrong.

7. When using Autowired annotation to inject dao, IDEA prompts that no available Bean can be found

If autowired is used in the above integration process, it will prompt this problem, as follows:
Insert picture description here
IDEA prompts us that there is no bean that can be injected, why does IDEA prompt us so, because we do not provide an implementation class for the dao interface, IDEA naturally cannot detect it, but We can ignore him, it will not affect the compilation and runtime, because Mybatis will implement an implementation class for us and inject it into the Spring container, so that there will be no problems at runtime, but if we look at this prompt, we It can be replaced by Resource, and there will be no problem.

8. The running program keeps appearing typeException

Most of this is caused by problems in mapper.xml. Check the mapper file carefully to see if there are any problems with the type, number, use of #, etc. of the parameters.
The above are some of the problems that may be encountered during the integration process. Naturally, they are sorted out to quickly locate the problem next time. If it can help you passing by, so much the better.

Three. Summary

This article sorts out the process of integrating SpringBoot and MyBatis and the problems that may be encountered. The integration process picks the main writing, and some of them are not written. The problems are common problems. In fact, no matter what SpringBoot integration is, these steps are all. The first step is to import dependencies, and the second step is to modify the configuration file. Then start coding. This is the main process, and the purpose of organizing is to make repeated mistakes by yourself, and also hope to help you passing by.

Guess you like

Origin blog.csdn.net/m0_46897923/article/details/115245892