Sharding-JDBC(七)update报错:Can not update sharding key

1.详细报错信息:

Caused by: org.apache.ibatis.exceptions.PersistenceException:
### Error updating database.  Cause: org.apache.shardingsphere.infra.exception.ShardingSphereException: Can not update sharding key since the updated value will change t_contract's data nodes.
### The error may exist in com/demo/module/contract/dao/ContractDao.java (best guess)
### The error may involve com.demo.module.contract.dao.ContractDao.updateById-Inline
### The error occurred while setting parameters
### SQL: UPDATE t_contract  SET CONTRACT_ID=?, NAME=?, ACCOUNT=?, CREATE_TIME=?, UPDATE_TIME=?  WHERE ID=?
### Cause: org.apache.shardingsphere.infra.exception.ShardingSphereException: Can not update sharding key since the updated value will change t_contract's data nodes.
        at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
        at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:199)
        at com.baomidou.mybatisplus.extension.service.impl.ServiceImpl.lambda$updateBatchById$3(ServiceImpl.java:194)
        at com.baomidou.mybatisplus.extension.toolkit.SqlHelper.lambda$executeBatch$0(SqlHelper.java:215)
        at com.baomidou.mybatisplus.extension.toolkit.SqlHelper.executeBatch(SqlHelper.java:179)
        ... 118 common frames omitted
Caused by: org.apache.shardingsphere.infra.exception.ShardingSphereException: Can not update sharding key since the updated value will change t_contract's data nodes.
        at org.apache.shardingsphere.sharding.route.engine.validator.dml.impl.ShardingUpdateStatementValidator.postValidate(ShardingUpdateStatementValidator.java:54)
        at org.apache.shardingsphere.sharding.route.engine.ShardingSQLRouter.lambda$createRouteContext$1(ShardingSQLRouter.java:57)
        at java.util.Optional.ifPresent(Optional.java:159)
        at org.apache.shardingsphere.sharding.route.engine.ShardingSQLRouter.createRouteContext(ShardingSQLRouter.java:57)
        at org.apache.shardingsphere.sharding.route.engine.ShardingSQLRouter.createRouteContext(ShardingSQLRouter.java:44)
        at org.apache.shardingsphere.infra.route.engine.impl.PartialSQLRouteExecutor.route(PartialSQLRouteExecutor.java:73)
        at org.apache.shardingsphere.infra.route.engine.SQLRouteEngine.route(SQLRouteEngine.java:53)
        at org.apache.shardingsphere.infra.context.kernel.KernelProcessor.route(KernelProcessor.java:54)
        at org.apache.shardingsphere.infra.context.kernel.KernelProcessor.generateExecutionContext(KernelProcessor.java:46)
        at org.apache.shardingsphere.driver.jdbc.core.statement.ShardingSpherePreparedStatement.createExecutionContext(ShardingSpherePreparedStatement.java:431)
        at org.apache.shardingsphere.driver.jdbc.core.statement.ShardingSpherePreparedStatement.addBatch(ShardingSpherePreparedStatement.java:500)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.ibatis.logging.jdbc.PreparedStatementLogger.invoke(PreparedStatementLogger.java:59)
        at com.sun.proxy.$Proxy446.addBatch(Unknown Source)
        at org.apache.ibatis.executor.statement.PreparedStatementHandler.batch(PreparedStatementHandler.java:58)
        at org.apache.ibatis.executor.statement.RoutingStatementHandler.batch(RoutingStatementHandler.java:69)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:63)
        at com.sun.proxy.$Proxy444.batch(Unknown Source)
        at com.baomidou.mybatisplus.core.executor.MybatisBatchExecutor.doUpdate(MybatisBatchExecutor.java:85)
        at org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:117)
        at com.baomidou.mybatisplus.core.executor.MybatisCachingExecutor.update(MybatisCachingExecutor.java:85)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.ibatis.plugin.Invocation.proceed(Invocation.java:49)
        at com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor.intercept(MybatisPlusInterceptor.java:83)
        at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:61)
        at com.sun.proxy.$Proxy443.update(Unknown Source)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:63)
        at com.sun.proxy.$Proxy443.update(Unknown Source)
        at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:197)
        ... 121 common frames omitted

2.问题原因:

核心报错内容:Can not update sharding key since the updated value will change t_contract’s data nodes.

问题原因: update语句中涉及了分片键值的更新,更新后的键值可能会导致数据所在分片位置,所以分片键的值不可更新。

3.解决方法:

将MybatisPlus版本升级到 3.4.1 以上,在实体类的 @TableFiled 注解中增加参数:updateStrategy = FieldStrategy.NEVER,意思是永远不更新该字段值。如下所示:

import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * <p>
 * 用户表
 * </p>
 *
 * @author ACGkaka
 * @since 2021-04-25
 */
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
@TableName("t_user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 主键
     */
    @TableId(value = "id")
    private Long id;

    /**
     * 用户名
     */
    @TableField("username")
    private String username;

    /**
     * 密码
     */
    @TableField("password")
    private String password;

    /**
     * 年龄
     */
    @TableField("age")
    private Integer age;

    /**
     * 创建时间
     */
    @TableField(value = "createTime", updateStrategy = FieldStrategy.NEVER)
    private LocalDateTime createTime;

    /**
     * 更新时间
     */
    @TableField("updateTime")
    private LocalDateTime updateTime;
}

整理完毕,完结撒花~

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
### 回答1: Spring Boot集成Sharding-JDBC可以实现分库分表的功能,提高数据库的性能和扩展性。具体步骤如下: 1. 引入Sharding-JDBC的依赖: ```xml <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>sharding-jdbc-core</artifactId> <version>4.1.1</version> </dependency> ``` 2. 配置Sharding-JDBC的数据源: ```yaml spring: shardingsphere: datasource: names: ds, ds1 ds: type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.jdbc.Driver jdbc-url: jdbc:mysql://localhost:3306/db username: root password: root ds1: type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.jdbc.Driver jdbc-url: jdbc:mysql://localhost:3306/db1 username: root password: root sharding: tables: user: actual-data-nodes: ds$->{..1}.user_$->{..1} table-strategy: inline: sharding-column: id algorithm-expression: user_$->{id % 2} ``` 3. 配置Sharding-JDBC的规则: ```yaml spring: shardingsphere: sharding: default-database-strategy: inline: sharding-column: id algorithm-expression: ds$->{id % 2} sharding-algorithms: database-inline: type: INLINE props: algorithm-expression: ds$->{id % 2} table-inline: type: INLINE props: algorithm-expression: user_$->{id % 2} ``` 4. 编写代码进行测试: ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public void addUser(User user) { userMapper.addUser(user); } @Override public User getUserById(Long id) { return userMapper.getUserById(id); } @Override public List<User> getAllUsers() { return userMapper.getAllUsers(); } } ``` 以上就是Spring Boot集成Sharding-JDBC的基本步骤,可以根据实际需求进行配置和调整。 ### 回答2: Sharding-JDBC是一个开源的基于JDBC的分库分表中间件,它可以对表数据进行分库、分表、分片等操作,从而实现高并发和高扩展性等需求。Spring Boot是一个基于Spring框架的全栈式Java开发框架,它简化了应用程序的搭建和开发,提供了诸如自动配置、依赖管理和运行时应用程序监控等功能。 Spring Boot集成Sharding-JDBC的过程如下: 1.添加Sharding-JDBC的依赖:在pom.xml文件中添加Sharding-JDBC的依赖。 2.配置连接池:在application.properties或application.yml中配置数据源的连接信息与连接池信息。 3.配置分库分表规则:在application.properties或application.yml中配置Sharding-JDBC的分库分表规则,可以通过多种方式配置。 4.编写Mapper和Service层代码:在Mapper和Service层中编写SQL语句以及对数据库进行操作的方法。 5.测试:编写测试代码对Sharding-JDBC进行测试,以确保其正确性和可用性。 以上就是Spring Boot集成Sharding-JDBC的过程,通过该过程可以实现高并发和高扩展性等需求,其具有简单易用和优秀的性能等特点,为企业级开发提供了一种高效、安全和可控的技术解决方案。 ### 回答3: 随着互联网技术的不断发展,越来越多的企业和项目需要使用分库分表技术来应对数据量的不断增大。而Sharding-JDBC是一个分库分表框架,它的出现给开发者提供了一种轻松便捷集成分库分表的方式。而Spring Boot则是一个非常流行的快速开发框架,它可以帮助开发者快速搭建应用程序。本文将介绍如何在Spring Boot中集成Sharding-JDBC。 第一步是引入相关依赖。在pom.xml文件中加入以下依赖: ``` <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>sharding-jdbc-core</artifactId> <version>5.0.0-alpha</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> ``` 第二步是配置Sharding-JDBC。我们要对分库分表进行配置,需要按照以下步骤进行: 1. 配置数据源(DataSources):我们需要配置每个数据库JDBC连接信息。 2. 配置数据源(DataSourceRule):将多个数据源合并成一个虚拟数据源,给程序使用。 3. 配置分表策略(TableRule):为每个数据表设置分表策略,指定分表算法和分表键等信息。 4. 配置分库策略(DatabaseShardingStrategy):为每个分表设置分库策略,指定分库算法和分库键等信息。 5. 配置分表算法(ShardingAlgorithm):设置分表算法。 6. 配置分库算法(ShardingAlgorithm):设置分库算法。 以上步骤可以参考Sharding-JDBC的官方文档。 第三步是将Sharding-JDBC注入到Spring Boot中。我们需要在配置类(通常是application.yml或application.properties文件)中配置数据源和Sharding-JDBC的相关信息。 ``` spring: sharding: jdbc: # 配置数据源 dataSources: ds0: url: jdbc:mysql://localhost:3306/db0?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8 username: root password: root ds1: url: jdbc:mysql://localhost:3306/db1?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8 username: root password: root # 配置数据源规则 dataSourceRule: # 主从配置,选择哪个数据源(ds0 或 ds1) masterDataSourceName: ds0 slaveDataSourceNames: ds1 # 配置分片规则 shardingRule: # 配置分表规则 tableRules: - logicTable: t_order # 逻辑表名 actualDataNodes: ds${0..1}.t_order_${0..1} # 真实表名 tableStrategy: standard: shardingColumn: order_id shardingAlgorithmName: t_order_inline # 配置分库规则 databaseShardingStrategy: standard: shardingColumn: user_id shardingAlgorithmName: database_inline # 配置分片算法 shardingAlgorithms: t_order_inline: type: INLINE props: algorithm-expression: t_order_${order_id % 2} database_inline: type: INLINE props: algorithm-expression: ds${user_id % 2} ``` 最后,在需要使用的地方使用即可。比如在服务类中注入DataSource即可使用。 总之,Spring Boot集成Sharding-JDBC并不复杂,只需要按照上述步骤配置即可。如果还有不清楚的地方,可以查看Sharding-JDBC的官方文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不愿放下技术的小赵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值