SpringBoot中整合Mybatis
整合步骤:
- 添加MyBatis和数据库驱动的依赖到
pom.xml
文件中。 - 配置数据源和MyBatis的SQL会话工厂。
- 创建Mapper接口和Mapper XML文件。
- 在Spring Boot应用的主类中启用Mapper接口扫描。
示例代码:
pom.xml
依赖配置:
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- MyBatis Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<!-- 数据库驱动,以MySQL为例 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
</dependencies>
application.properties
配置文件:
spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.yourpackage.model
Mapper接口:
package com.yourpackage.mapper;
public interface UserMapper {
User selectUserById(int id);
}
Mapper XML文件:
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yourpackage.mapper.UserMapper">
<select id="selectUserById" parameterType="int" resultType="com.yourpackage.model.User">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
启用Mapper扫描:
package com.yourpackage;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.yourpackage.mapper")
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
以上代码展示了如何在Spring Boot项目中整合MyBatis。通过配置数据源、指定Mapper位置和设置类别别名,你可以使用注解或XML配置的方式来编写Mapper接口和映射SQL语句。最后,通过@MapperScan
注解启用Mapper接口扫描。
评论已关闭