Seventeen, Spring Boot integration MyBatis detailed steps (two ways)
@
- Seventeen, Spring Boot integration MyBatis detailed steps (two ways)
- 1. Spring Boot configuration MyBatis detailed steps
- 2. Finally:
The official documentation for MyBatis:https://mybatis./
For more details about learning MyBatis, you can move to: ✏️✏️✏️MyBatis_ChinaRainbowSea's Blog - CSDN Blogs 。
1. Spring Boot configuration MyBatis detailed steps
- First, we create the database for the relevant test, the data table. It is as follows:
CREATE DATABASE `springboot_mybatis`
USE `springboot_mybatis`
CREATE TABLE `monster` (
`id` int not null auto_increment,
`age` int not null,
`birthday` DATE DEFAULT NULL,
`email` VARCHAR(255) DEFAULT NULL,
`gender` CHAR(1) DEFAULT null,
`name` VARCHAR(255) DEFAULT NULL,
`salary` DOUBLE not NULL,
PRIMARY KEY(`id`)
)
SELECT * from monster
INSERT INTO `monster` (`id`,`age` ,`birthday`,`email`,`gender`,`name`,`salary`)
VALUES (1,20,'2000-10-10','nmw@','male','Gyuumao',9000.99)
INSERT INTO `monster` (`id`,`age` ,`birthday`,`email`,`gender`,`name`,`salary`)
VALUES (2,10,'2000-12-12','bgj@','daughter','(slang) fairy, elf, leprechaun etc',9999.99)
- Import the relevant
jar
Dependencies. Here we are using the Druid database connection pool and we also need to import theThe.
<!-- pull into mybatis starter-->
<!-- /artifact//mybatis-spring-boot-starter -->
<dependency>
<groupId></groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
Introducing the Druid databasejar
Dependency.
<!-- pull into druid dependencies-->
<dependency>
<groupId></groupId>
<artifactId>druid</artifactId>
<version>1.1.17</version>
</dependency>
All the jar dependencies in the file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="/POM/4.0.0"
xmlns:xsi="http:///2001/XMLSchema-instance"
xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.">
<modelVersion>4.0.0</modelVersion>
<groupId></groupId>
<artifactId>springboot_mybaits</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- import (data)SpringBoot parent project-style of writing (grammar)-->
<parent>
<groupId></groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.3</version>
</parent>
<!-- import (data)webProject Scene Launcher:会自动import (data)和webdevelopment-relatedjarPackage all dependencies【storehouse/jar】-->
<!-- I'll explain later.spring-boot-starter-web What exactly are the relevant dependencies introduced-->
<dependencies>
<!-- pull into web starter dependencies-->
<dependency>
<groupId></groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- pull into mybatis starter-->
<!-- /artifact//mybatis-spring-boot-starter -->
<dependency>
<groupId></groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<!-- pull into mysql drive (vehicle wheel): Here the teacher uses version arbitration 8.0.26-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- pull into配置处理器-->
<dependency>
<groupId></groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
<!--pull intolombok-->
<dependency>
<groupId></groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- pull into test stater -->
<dependency>
<groupId></groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- pull into druid dependencies-->
<dependency>
<groupId></groupId>
<artifactId>druid</artifactId>
<version>1.1.17</version>
</dependency>
</dependencies>
</project>
- Write a Java bean object that corresponds to the data table.
Special Instructions:
Here's how to use the
@JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")
annotation. to set a time format for assigning the time in the data table to the time attribute on the bean object.
pattern = "yyyy-MM-dd"
is to set the formatting style of the time displaytimezone = "GMT+8"
is to set the time zone difference. Here we have China in the Eastern Hemisphere with a time difference of +8 hours.Note: This annotation is only effective for front-end display, but not for back-end, console display.
- Switch Spring Boot's default HikariCP database connection pool to the one we want.
Druid
Database connection pooling.
Here we switch by configuring the class.
package ;
import ;
import ;
import ;
import ;
import ;
@Configuration
public class DruidDataSourceConfig {
@ConfigurationProperties(value = "") // retrieve under the class path
// such information,and provides the following corresponding setXX perform an assignment operation
@Bean
public DataSource dataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
return druidDataSource;
}
}
Create a file under the resource class path called documentation, configuration writing, and related for, information about the Druid database connection pool. The following is the list:
server:
port: 9090 # take note of:Using spaces
spring:
datasource:
driver-class-name:
username: root
password: MySQL123
url: jdbc:mysql://localhost:3306/springboot_mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
- Write a scene starter for the project
package ;
import ;
import ;
import ;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext ioc = (, args);
}
}
- Run a test to see if we have successfully switched to the Duird data connection pool we want, because if you test in Spring Boot, you have to write the corresponding project launcher, otherwise, you can't test it and it will report an error.
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@SpringBootTest(classes = ) // together with main Different needs are indicated Which one was tested?Classresemble
public class ApplicationTest {
@Resource
private JdbcTemplate jdbcTemplate;
@Test
public void t1() {
// Output to see what the current data source is
(().getClass());
}
}
- Create a mapper/dao package, and under that package, create a package named
MonsterMapper
interface, by way of a proxy class, under which to write the methods of the SQL statement that we want to execute the business.
package ;
import ;
import ;
/**
* Using @Mapper in the Mapper interface scans for and injects the Mapper interface object into the
*/
@Mapper // package scanning, with this annotation then
public interface MonsterMapper {
// method Returns a Monster object based on its id
public Monster getMonsterById(Integer id);
}
Special Notes:
In this case, we are using the
@Mapper
annotation. What this annotation does is that it makes Spring Boot scan for this class when it loads it. And thus find this class. This way we don't need to configure additionalPackage scanned. 。
- Create the corresponding package under the corresponding corresponding package to create the corresponding SQl statement for the
xml
file. As follows
<?xml version="1.0" encoding="UTF-8"? >;DOCTYPE mapper PUBLIC "-DTD
<!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN"
"/dtd/">.
< mapper namespace="">
<! --
1. Scan all the implementations of the dao interface and add them to the ioc container.
2. Here, the dao interface is the mapper interface.
-->
<! --configure getMonsterById -->
<select resultType="">
select * from monster where id = #{id}
</select>
<! -- elect * from `monster` where id = #{id} Note: not single-quote processing -->
</mapper>!
Also needed in. The Mybatis package scan path is configured in the following file;
mybatis:
# Specify which
mapper-locations: classpath:mapper/*.xml
server.
port: 9090 # Note: Use spaces.
spring.
datasource.
driver-class-name: driver-address: driver-address: driver-address: driver-address
username: root
password: MySQL123
url: jdbc:mysql://localhost:3306/springboot_mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
mybatis.
# Specify what to scan for
mapper-locations: classpath:mapper/*.xml
# Specify via config-location You can configure mybatis in the traditional way.
# config-location.
# We can configure mybatis in the traditional way.
# For example, to configure the original typeAliases.
# There's a lot more to configure, but we'll get to that when we get to it.
# type-aliases-package.
# configuration.
# log-impl.
# map-underscore-to-camel-case: true
# Teacher's Note: Configure mybatis in two ways to choose: If the configuration is relatively simple, it is directly in the configuration
# If the configuration is simpler, you can directly configure mybatis in a
Run the test:
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@SpringBootTest(classes = ) // together with main Different needs are indicated Which one was tested?Classresemble
public class ApplicationTest {
@Resource
private MonsterMapper monsterMapper;
@Test
public void getMonsterById() {
Monster monsterById = (1);
(monsterById);
}
}
- Write the corresponding Severl business process
First, write its interface:
package ;
import ;
public interface MonsterService {
// according toid come (or go) back Monster boyfriend
public Monster getMonsterById(Integer id);
}
In writing an implementation class for its interface, the
package ;
import ;
import ;
import ;
import ;
import ;
@Service
public class MonsterServiceImpl implements MonsterService {
// mountingMonsterMapper
@Resource
private MonsterMapper monsterMapper;
@Override
public Monster getMonsterById(Integer id) {
return (id);
}
}
Run the test:
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@SpringBootTest(classes = ) // together with main Different needs are indicated Which one was tested?Classresemble
public class ApplicationTest {
// mountMonsterService
@Resource
private MonsterService monsterService;
// beta (software) MonsterService
@Test
public void getMonsterById2() {
Monster monster = (2);
(monster);
}
}
- Write the corresponding Controller to handle the display on the front-end.
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@Controller
public class MonsterController {
// mountingMonsterService
@Resource
private MonsterService monsterService;
@ResponseBody
@GetMapping("/monster")
public Monster getMonsterById( @RequestParam(value = "id") Integer id) {
return (id);
}
}
Run the test: Note: The port we configured here is 9090, not 8080.
2. Finally:
"In this final chapter, I would like to express my gratitude to each and every one of my readers. Your attention and responses have been a source of motivation for me to create, and I have drawn endless inspiration and courage from you. I will keep your encouragement in my heart and continue to struggle in other areas. Thanks to you all, we will always meet again at some point."