shardingsphere整合mybatis
时间: 2024-01-15 18:18:04 浏览: 35
以下是ShardingSphere整合MyBatis的步骤:
1.添加ShardingSphere和MyBatis的依赖:
```xml
<!-- ShardingSphere -->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-core</artifactId>
<version>${shardingsphere.version}</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.version}</version>
</dependency>
```
2.配置ShardingSphere数据源和分片规则:
```yaml
spring:
shardingsphere:
datasource:
names: ds0, ds1
ds0:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db0?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8
username: root
password: root
ds1:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db1?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8
username: root
password: root
sharding:
tables:
user:
actual-data-nodes: ds$->{0..1}.user_$->{0..1}
table-strategy:
inline:
sharding-column: id
algorithm-expression: user_$->{id % 2}
key-generator:
column: id
type: SNOWFLAKE
```
3.在MyBatis的Mapper接口中定义SQL语句:
```java
@Mapper
public interface UserMapper {
@Insert("insert into user (id, name) values (#{id}, #{name})")
int insert(User user);
@Select("select * from user")
List<User> selectAll();
}
```
4.在MyBatis的Mapper XML文件中定义SQL语句:
```xml
<mapper namespace="com.example.demo.mapper.UserMapper">
<insert id="insert" parameterType="com.example.demo.entity.User">
insert into user (id, name) values (#{id}, #{name})
</insert>
<select id="selectAll" resultType="com.example.demo.entity.User">
select * from user
</select>
</mapper>
```
5.在Service中调用Mapper接口:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public int insert(User user) {
return userMapper.insert(user);
}
@Override
public List<User> selectAll() {
return userMapper.selectAll();
}
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)