shardingsphere
shardingsphere copied to clipboard
Can support associated query??
Pom dependence:
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-jdbc-core</artifactId>
<version>3.1.0</version>
</dependency>
<!-- mybatis分页 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.0</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<!-- jdbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>1.5.14.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
Mybatis SQL:
select * from pay_order
where payOrderId = (
select payOrderId from pay_suborder
where paySubOrderId = #{paySubOrderId,jdbcType=VARCHAR}
and dbPart BETWEEN #{lastDbPart,jdbcType=INTEGER} and #
{dbPart,jdbcType=INTEGER}
)
and dbPart BETWEEN #{lastDbPart,jdbcType=INTEGER} and #{dbPart,jdbcType=INTEGER}
limit 1;
spring boot database config
package com.yy.onepiece.pay.persist.base.config;
import com.yy.onepiece.pay.persist.DbConfigConstant;
import com.yy.onepiece.pay.persist.base.config.sharding.ModuloShardingAlgorithm;
import com.alibaba.druid.pool.DruidDataSource;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import io.shardingsphere.api.config.rule.ShardingRuleConfiguration;
import io.shardingsphere.api.config.rule.TableRuleConfiguration;
import io.shardingsphere.api.config.strategy.StandardShardingStrategyConfiguration;
import io.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;
/**
* Created by zhangzhe on 2018/7/17.
*/
@Configuration
@EnableTransactionManagement
public class PrimaryDataSourceConfig {
@Bean(initMethod = "init", destroyMethod = "close", name = DbConfigConstant.PRIMARY_DATASOURCE)
@Primary
@ConfigurationProperties(prefix = DbConfigConstant.PRIMARY_DATASOURCE_CONFIG_PREFIX)
public DataSource primaryDataSource() {
DruidDataSource dataSource = new DruidDataSource();
return dataSource;
}
@Bean(name = "shardingDataSource")
@DependsOn(DbConfigConstant.PRIMARY_DATASOURCE)
public DataSource getShardingDataSource(@Qualifier(DbConfigConstant.PRIMARY_DATASOURCE) DataSource dataSource) throws SQLException {
Map<String, DataSource> dsMap = Maps.newHashMap();
dsMap.put("luffy_order", dataSource);
Properties properties=new Properties();
properties.setProperty("sql.show","true");
return ShardingDataSourceFactory.createDataSource(dsMap, getShardingRuleConfiguration(), new HashMap<String, Object>()
, properties);
}
@Bean(name = DbConfigConstant.PRIMARY_TRANSACTIONMANAGER)
@DependsOn(DbConfigConstant.PRIMARY_DATASOURCE)
@Primary
public DataSourceTransactionManager transactionManager(@Qualifier("shardingDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
private static ShardingRuleConfiguration getShardingRuleConfiguration() {
ShardingRuleConfiguration shardingRuleConfiguration = new ShardingRuleConfiguration();
TableRuleConfiguration orderTableRuleConfig = new TableRuleConfiguration();
orderTableRuleConfig.setLogicTable("pay_order");
orderTableRuleConfig.setActualDataNodes("luffy_order.pay_order_${201901..201912}");
TableRuleConfiguration subOrderTableRuleConfig = new TableRuleConfiguration();
subOrderTableRuleConfig.setLogicTable("pay_suborder");
subOrderTableRuleConfig.setActualDataNodes("luffy_order.pay_suborder_${201901..201912}");
TableRuleConfiguration refundTableRuleConfig = new TableRuleConfiguration();
refundTableRuleConfig.setLogicTable("pay_refund_order");
refundTableRuleConfig.setActualDataNodes("luffy_order.pay_refund_order_${201901..201912}");
TableRuleConfiguration transferTableRuleConfig = new TableRuleConfiguration();
transferTableRuleConfig.setLogicTable("pay_transfer_account_order");
transferTableRuleConfig.setActualDataNodes("luffy_order.pay_transfer_account_order_${201901..201912}");
TableRuleConfiguration transferSubTableRuleConfig = new TableRuleConfiguration();
transferSubTableRuleConfig.setLogicTable("pay_transfer_account_sub_order");
transferSubTableRuleConfig.setActualDataNodes("luffy_order.pay_transfer_account_sub_order_${201901..201912}");
shardingRuleConfiguration.getTableRuleConfigs().add(orderTableRuleConfig);
shardingRuleConfiguration.getTableRuleConfigs().add(subOrderTableRuleConfig);
//shardingRuleConfiguration.getTableRuleConfigs().add(refundTableRuleConfig);
shardingRuleConfiguration.getTableRuleConfigs().add(transferTableRuleConfig);
shardingRuleConfiguration.getTableRuleConfigs().add(transferSubTableRuleConfig);
shardingRuleConfiguration.getBindingTableGroups()
.add("pay_order,pay_suborder,pay_transfer_account_order,pay_transfer_account_sub_order");
shardingRuleConfiguration.setDefaultTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("dbPart"
, new ModuloShardingAlgorithm()));
shardingRuleConfiguration.setDefaultDataSourceName("luffy_order");
return shardingRuleConfiguration;
}
}
package com.yy.onepiece.pay.persist.base.config;
import com.yy.onepiece.pay.persist.DbConfigConstant;
import com.yy.onepiece.pay.persist.MyBatisConfig;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import javax.sql.DataSource;
import io.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource;
/**
* Created by zhangzhe on 2018/7/17.
*/
@Configuration
@MapperScan(basePackages = "com.yy.onepiece.pay.persist.base.mapper", sqlSessionFactoryRef = DbConfigConstant.PRIMARY_SQLSESSIONFACTORY)
public class PrimaryMyBatisMapperConfig {
@Bean(DbConfigConstant.PRIMARY_MYBATISCONFIG)
@ConfigurationProperties(prefix = DbConfigConstant.PRIMARY_MYBATIS_CONFIG_PREFIX)
public MyBatisConfig myBatisConfig() {
return new MyBatisConfig();
}
@Bean(name = DbConfigConstant.PRIMARY_SQLSESSIONFACTORY)
@DependsOn("shardingDataSource")
public SqlSessionFactory primarySqlSessionFactory(@Qualifier("shardingDataSource") DataSource dataSource
, @Qualifier(DbConfigConstant.PRIMARY_MYBATISCONFIG) MyBatisConfig primaryMyBatisConfig, ApplicationContext acx)
throws Exception {
System.out.println(dataSource);
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
factory.setDataSource(dataSource);
factory.setConfigLocation(acx.getResource(primaryMyBatisConfig.getConfigLocation()));
factory.setTypeAliasesPackage(primaryMyBatisConfig.getTypeAliasesPackage());
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources;
resources = resolver.getResources(primaryMyBatisConfig.getMapperLocation());
factory.setMapperLocations(resources);
return factory.getObject();
}
}
when I run my test case, debug log is below:
12:02:04.297 [main] INFO c.alibaba.druid.pool.DruidDataSource 785 - {dataSource-1} inited
io.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource@421a4ee1
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
12:02:20.863 [main] INFO c.y.o.test.sharding.ShardingTest 57 - Started ShardingTest in 42.613 seconds (JVM running for 45.01)
Creating a new SqlSession
Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@49fe3142]
JDBC Connection [io.shardingsphere.shardingjdbc.jdbc.core.connection.ShardingConnection@4487c0c2] will be managed by Spring
==> Preparing: select * from pay_order where payOrderId = ( select payOrderId from pay_suborder where paySubOrderId = ? and dbPart BETWEEN ? and ? ) and dbPart BETWEEN ? and ? limit 1;
==> Parameters: SA915778200512946176(String), 201812(Integer), 201901(Integer), 201812(Integer), 201901(Integer)
Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@49fe3142]
Transaction synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@49fe3142]
Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@49fe3142]
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: java.lang.NullPointerException
### The error may exist in file [E:\workspace\gitproject\zoro\zoro-pay\zoro-pay-persist\target\classes\mappers\base\PayOrderExtMapper.xml]
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: select * from pay_order where payOrderId = ( select payOrderId from pay_suborder where paySubOrderId = ? and dbPart BETWEEN ? and ? ) and dbPart BETWEEN ? and ? limit 1;
### Cause: java.lang.NullPointerException
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:79)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:447)
at com.sun.proxy.$Proxy41.selectOne(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.selectOne(SqlSessionTemplate.java:167)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:82)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:53)
at com.sun.proxy.$Proxy42.getPayOrderBySubOrderId(Unknown Source)
at com.yy.onepiece.test.sharding.PaymentRepository.getPayOrderBySubOrderId(PaymentRepository.java:114)
at com.yy.onepiece.test.sharding.PaymentRepository$$FastClassBySpringCGLIB$$2fb360fd.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
at com.yy.onepiece.test.sharding.PaymentRepository$$EnhancerBySpringCGLIB$$edff288b.getPayOrderBySubOrderId(<generated>)
at com.yy.onepiece.test.sharding.ShardingTest.testQuery(ShardingTest.java:55)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: java.lang.NullPointerException
### The error may exist in file [E:\workspace\gitproject\zoro\zoro-pay\zoro-pay-persist\target\classes\mappers\base\PayOrderExtMapper.xml]
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: select * from pay_order where payOrderId = ( select payOrderId from pay_suborder where paySubOrderId = ? and dbPart BETWEEN ? and ? ) and dbPart BETWEEN ? and ? limit 1;
### Cause: java.lang.NullPointerException
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:150)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:77)
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.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:434)
... 50 more
Caused by: java.lang.NullPointerException
at io.shardingsphere.shardingjdbc.jdbc.core.statement.ShardingPreparedStatement.execute(ShardingPreparedStatement.java:139)
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.$Proxy53.execute(Unknown Source)
at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:63)
at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:79)
at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:63)
at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:324)
at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109)
at com.github.pagehelper.PageInterceptor.intercept(PageInterceptor.java:141)
at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:61)
at com.sun.proxy.$Proxy51.query(Unknown Source)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148)
... 57 more
12:02:22.377 [Thread-1] INFO o.s.c.a.AnnotationConfigApplicationContext 984 - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@748741cb: startup date [Sun Feb 17 12:01:39 CST 2019]; root of context hierarchy
12:02:22.404 [Thread-1] INFO c.alibaba.druid.pool.DruidDataSource 1534 - {dataSource-1} closed
Process finished with exit code -1
what's wrong?? sharding jdbc not support associated query??
@AllenTan thanks for your feedback, I have reproduced this error in my local, sharding-key of subquery can't parse correctly, then routResult get a null point exception, we'll try to fix this bug.
thanks, shere conditiion column has none owner, cause sharding condition is wrong