3月第三讲Spring Boot系列-集成mybatis
在Spring Boot项目中集成MyBatis,首先需要在项目的pom.xml
中添加MyBatis和数据库驱动的依赖。以下是一个简化的例子:
<dependencies>
<!-- Spring Boot相关依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!-- 数据库驱动,以MySQL为例 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<!-- 其他必要的依赖 -->
</dependencies>
接下来,在application.properties
或application.yml
中配置数据库连接信息和MyBatis的相关设置:
# 数据库连接信息
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 设置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.yourpackage.model
创建Mapper接口和Mapper XML文件。例如:
// UserMapper.java
package com.yourpackage.mapper;
public interface UserMapper {
User selectUserById(int id);
}
<!-- UserMapper.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<!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>
在Spring Boot的主类或配置类中,通过@MapperScan
注解指定Mapper接口的位置:
// YourApplication.java
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);
}
}
最后,可以在Service层中注入Mapper并使用:
// UserService.java
package com.yourpackage.service;
import com.yourpackage.mapper.UserMapper;
import com.yourpackage.model.User;
import org.springframe
评论已关闭