Integration Steps
To integrate MyBatis with a Spring Boot project, start by adding necessary dependencies to your pom.xml:
<dependencies>
<!-- MySQL Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<!-- MyBatis Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.0</version>
</dependency>
<!-- Druid Connection Pool -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<!-- FastJSON -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
</dependencies>
Subsequent steps (e.g., configuring data sources, defining Mapper interfaces, and creating XML mapping files) follow standard SSM (Spring + SpringMVC + MyBatis) practices.
Common Issues and Solutions
1. Deprecated Driver Warning
Problem: Warning about loading com.mysql.jdbc.Driver (deprecated).
Solution: Use the new driver class com.mysql.cj.jdbc.Driver in application.properties:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
2. DAO Interafce Bean Not Found
Problem: Service layer fails to inject DAO interfaces (e.g., No bean named 'userMapper' available).
Solution: Add @Repository annotation to DAO interfaces to enable Spring bean management:
@Repository
public interface UserMapper {
User findUserInfo(int id);
}
3. Mapper Not Scanned
Problem: Invalid bound statement (not found) error, indicating MyBatis cannot locate Mapper methods.
Solutions:
- Namespace Mismatch: Ensure the XML file's
namespacematches the fully qualified DAO interface name (e.g.,com.example.dao.UserMapper). - Interface-XML Naming: DAO interface name must match the XML file name (e.g.,
UserMapper.javaandUserMapper.xml). - Resource Scanning: Configure Maven to scan XML files in
src/main/javaby adding the following topom.xml:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
Additionally, use @MapperScan in the main class to specify the DAO package (e.g., @MapperScan("com.example.dao")).
4. Time Zone Error
Problem: The server time zone value '�й���ʱ��' is unrecognized when connecting to MySQL.
Solution: Append serverTimezone=GMT%2B8 to the database URL in application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/dbname?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
5. Authentication Failure
Problem: Access denied for user 'root'@'localhost' due to incorrect credentials.
Solution: Verify spring.datasource.username and spring.datasource.password in application.properties match your MySQL credentials.