During project startup, the Spring Boot Starter loads and initializes components based on convention information. Therefore, the introduction of the Starter for the project can be achieved out of the box. So mybatis-spring-boot-starter can help you quickly build a MyBatis application based on Spring Boot.
⭐ next to get you started integrating MyBatis in the Spring Boot project!
Import the following dependencies into the POM.xml file:
<! -- MyBatis Integration With Spring Boot -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<! -- @data, @tostring -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<! Mysql driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<! -- log4j prints SQL execution logs,.yml configuration -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
<version>1.3.8. RELEASE</version>
</dependency>
Copy the code
Note: this dependency is provided by MyBatis official integration with Spring Boot, not Spring Boot official integration with MyBatis, so the
version number cannot be omitted!
As we all know, MyBatis has two core components: SqlSessionFactory and Mapper interface. The former is used for database connections and the latter for SQL mappings. When we use MyBatis based on Spring, we also want to ensure that these two components are present in the Spring environment.
After the mybatis-spring-boot-starter dependency is introduced, it will automatically complete the following tasks:
- Automatic detection of existing
DataSource
- using
SqlSessionFactoryBean
Create and registerSqlSessionFactory
- Create and register
SqlSessionTemplate
The instance - Automatic scanning
Mappers
Interface and register it in the Spring context for easy injection
Mysql > select * from sys_user;
Field | Type | Comment |
---|---|---|
Id 🔑 | bigint(20) NOT NULL | The user ID |
username | varchar(50) NULL | The user name |
varchar(50) NULL | ||
password | varchar(80) NULL | password |
phoneNum | varchar(20) NULL | The phone number |
Create the User entity class
Note: the entity class name User does not match the sys_USER table name in the database, so it cannot be mapped automatically. Therefore, manual mapping should be carried out through the resultType attribute when usermapper. XML is written. Phone and phoneNum are mapped through the AS alias in the Select statement.
@Data
@ToString
public class User {
private int id;
private String username;
private String email;
private String password;
private String phone;
}
Copy the code
Mapper interfaces:
@Mapper
public interface UserMapper {
List<User> selectAllUsers(a);
}
Copy the code
🧠 If you have more than one @mapper, it is a bit troublesome to annotate one by one. In this case, you can use @mapperscan (basePackages = “com.wyk.mybatis. Dao “) instead.
@Configuration
@MapperScan(basePackages = "com.wyk.mybatis.dao")
public class MyBatisConfiguration {}Copy the code
For SQL statements, we can write them as annotations or as XML configuration files, which are used here to demonstrate:
Front: in the resource directory com/wyk/new mybatis mapper/UserMapper. The XML mapping file.
<! DOCTYPEmapper PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wyk.mybatis.dao.UserMapper">
<select id="selectAllUsers" resultType="user">-- phoneNum As phone: select ID, username, email, password, phoneNum As phone -- Mapping with inconsistent table names from sys_user;</select>
</mapper>
Copy the code
The SQL mappings are basically configured, but the database is not connected yet, so you configure them in application.yml.
spring:
datasource:
url: jdbc:mysql://localhost:3306/mybatis? useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
mybatis:
# Entity category name -- package path
type-aliases-package: com.wyk.mybatis.entity
# map file location
mapper-locations: classpath*:com/wyk/mybatis/mapper/*Mapper.xml
configuration:
Print SQL statements using logs
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
Copy the code
OK! Next test in the test class:
@SpringBootTest
class MybatisApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void contextLoads(a) { List<User> users = userMapper.selectAllUsers(); users.forEach(System.out::println); }}Copy the code
Running results:
🤨Spring Boot integrated MyBatis basic operations on this demonstration, more operations and configuration please refer to the official documentation