MyBatis与Spring Cloud集成
在Spring Cloud项目中,我们可以使用Spring Cloud Alibaba的spring-cloud-starter-alibaba-nacos-config
来配置MyBatis的数据源和事务管理器。以下是一个基本的配置示例:
- 在
pom.xml
中添加MyBatis和Spring Cloud Alibaba的依赖:
<dependencies>
<!-- Spring Cloud Alibaba Nacos Config -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!-- MyBatis -->
<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
或application.yml
中配置MyBatis和数据源:
spring:
datasource:
url: jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC
username: your_username
password: your_password
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml # 指定MyBatis的mapper文件位置
type-aliases-package: com.yourpackage.model # 指定别名包路径
- 创建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="User">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
- 在Spring服务中使用MyBatis的Mapper:
// UserService.java
package com.yourpackage.service;
import com.yourpackage.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final UserMapper userMapper;
@Autowired
public UserService(UserMapper us
评论已关闭