Connect to mysql database and integrate mybatis-plus under springboot 3

test example

Integrate mysql and mybatis-plus under Springboot 3.x version, and conduct a simple test to solve common bugs encountered in the implementation process.

Introduce dependencies

<!-- 数据库驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
<!-- mybatis-plus 3.5.3 才支持 spring boot 3-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.3</version>
</dependency>

Configure application.yml

# mysql 配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/community?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
    username: root
    password: yumuing
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      maximum-pool-size: 15
      minimum-idle: 5
      idle-timeout: 30000
# mybatis-plus 配置

mybatis-plus:
  configuration:
    map-underscore-to-camel-case: true
    auto-mapping-behavior: full
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    use-generated-keys: true
  mapper-locations: classpath*:mapper/**/*Mapper.xml
  type-aliases-package: top.yumuing.community.entity

Create a MySQL database

Create the community database and run the following SQL code to complete the creation of the data table:

INSERT INTO user (id, name, email) VALUES
(1, 'Jone', '[email protected]'),
(2, 'Jack','[email protected]'),
(3, 'Tom','[email protected]'),
(4, 'Sandy', '[email protected]'),
(5, 'Billie','[email protected]');

Query OK, 5 rows affected (0.01 sec)
Records: 5  Duplicates: 0  Warnings: 0
mysql> DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int DEFAULT NULL,
  `name` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `age` int DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Test the MySQL connection

@Resource
DataSource dataSource;

@Test
void contextLoadsOne() throws Exception{
    
    
    System.out.println("获取的数据库连接为:"+dataSource.getConnection());
}

If the console outputs the following content, the MySQL connection configuration is successful:

获取的数据库连接为:HikariProxyConnection@54056059 wrapping com.mysql.cj.jdbc.ConnectionImpl@5611bba

Test integration Mybatis-plus simple configuration

@Resource
private UserMapper userMapper;

@Test
void contextLoadsTwo() {
    
    
    List<User> list = userMapper.selectList(null);
    list.forEach(item-> System.out.println(item));
}

If the console outputs the following content, the configuration of Mybatis-plus is successful

User(id=1, name=张三, age=20)
User(id=2, name=李四, age=22)
User(id=3, name=王五, age=30)

Of course, we can also use the MybatisX plug-in to generate mapper.class, mapper.xml, service.class, serviceImpl.class, the steps are as follows:

MybatisX use

Moreover, we can also use the MybatisX plug-in to implement the SQL code corresponding to mapper in the xml file, and write the method name in mapper.class that we want to generate code in xml. It must start with select, insert, update, etc. After that, there will be a corresponding prompt, just select it. After completion, go forward a few grids, the method name will turn red, select the error report, right click and select the following content to generate the relevant code:

Screenshot_20230208_000238

The code generated by selectAllByIdOrderByAge in the xml file is as follows:

<sql id="Base_Column_List">
    id,name,age
</sql>
<select id="selectAllByIdOrderByAge" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List"/>
    from user
    where
    id = #{id,jdbcType=NUMERIC}
    order by age
</select>

The test code is as follows:

@Test
void cotextLoadsFour(){
    
    
    List<User> users = userMapper.selectAllByIdOrderByAge(3);
    users.forEach(item-> System.out.println(item));
}

Bug summary

Property ‘sqlSessionFactory’ or ‘sqlSessionTemplate’ are required

The springboot 3 version integrates the mybatis 3.0.5 version console to report an error Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required, and the NestedIOException class is directly deleted in the Spring 6 version. Yes, deleted directly. However, the old version of MyBatis has not been updated synchronously, so it is directly reported as red. And mybatis-plus, which integrates mybatis, will naturally become popular.

In the early morning of November 26, 2022, mybatis-spring-boot officially released version 3.0.0, which fully supports Spring Boot 3. mybatis-plus also supports Spring Boot 3 in 3.5.3 on 2022.12.28. The best solution is to upgrade the version.

Could not autowire. No beans of ‘DataSource’ type found

  1. Check the project structure, whether the location of the main startup class is correct
  2. Replace the automatic assembly @Autowired with @Resource

Driver com.mysql.jdbc.Driver claims to not accept jdbcUrl

The error is the configuration file path error, focus on checking the url path, the test after 3306 is the database name, pay attention to modify it to the existing database name of the database

mysql8.x specified URL jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8

Cannot resolve method ‘assertEquals’ in ‘Assert’

In the test method, use this method to report an error, and the Assert package of import org.junit.Assert; is not introduced. The solution is as follows:

  1. Introduce junit dependency

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    
  2. Import the correct package import org.junit.Assert; Assert

Injection of resource dependencies failed

Test method console output: Injection of resource dependencies failed

Make sure that the object of the error is userMapper, and find that MapperScan is not specified, the solution is as follows:

Add in the startup class: @MapperScan("top.yumuing.community.mapper")

Could not autowire. No beans of ‘DataSource’ type found.

Compile error: Could not autowire. No beans of 'DataSource' type found. The code is as follows:

@Autowired
DataSource dataSource;

Modify @Autowired to @Resource to solve

Could not autowire. No beans of ‘UserMapper’ type found.

@Autowired
private UserMapper userMapper;

Modify @Autowired to @Resource to solve
Ask for likes and forward

Guess you like

Origin blog.csdn.net/yumuing/article/details/128928272