Gentle0503 2020-11-18 21:05 采纳率: 64.7%
浏览 217
已结题

JPA 的动态切换数据源切换失败,请问怎么回事?????

  • 后端代码
  • public class DynamicDataSource extends AbstractRoutingDataSource {
    
    	private static final ThreadLocal<String> contextHolder = new ThreadLocal();
    	
    	@Override
        protected Object determineCurrentLookupKey() {
    		String string = contextHolder.get();
    		System.out.println("当前数据源:"+string);
            return string;
        }
    
    	public static void setCustomerType(String customerType) {
    		contextHolder.set(customerType);
    	}
    
    	public static String getCustomerType() {
    		return (String) contextHolder.get();
    	}
    
    	public static void clearCustomerType() {
    		contextHolder.remove();
    	}
    }
    /**
     * 切换数据源Advice
     */
    @Aspect
    @Order(-10)// 保证该AOP在@Transactional之前执行
    @Component
    public class DynamicDataSourceAspect {
    
        //@Before(value="execution(* com.bster.projectM.service..*.*(..))")
    	@Before(value = "@annotation(source)")
        public void changeDataSource(JoinPoint jp,TargetDataSource source) throws Throwable {
    		System.out.println("切库操作:"+source.value());
    		DynamicDataSource.setCustomerType(source.value());
    		System.out.println("当前数据源:"+source.value());
        }
        @After(value = "@annotation(source)")
        public void restoreDataSource(JoinPoint point,TargetDataSource source) {
        	System.out.println("切库还原:"+source.value());
        	DynamicDataSource.clearCustomerType();
    		System.out.println("当前数据源:"+source.value());
        }
    }
     
    // 在方法上使用,用于指定使用哪个数据源
    @Target({ ElementType.METHOD,ElementType.TYPE })
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface TargetDataSource {
        String value() default DATASOURCE1;;
    	
    	String DATASOURCE1="d1";
    	
    	String DATASOURCE2="d2";
    }

    xml文件配置如下:

  •  <bean id="d1" class="org.apache.commons.dbcp2.BasicDataSource" primary="true">
            <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
            <property name="url" value="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=d1"/>
            <property name="username" value="sa"/>
            <property name="password" value="123456"/>
        </bean>
     
     
        <bean id="d2" name="d2" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
            <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
            <property name="url" value="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=d2"/>
            <property name="username" value="sa"/>
            <property name="password" value="123456"/>
        </bean>
     
        <!--动态选择数据源-->
        <bean id="dataSource" class="com.bster.projectM.config.datasource.DynamicDataSource" >
            <property name="targetDataSources">
                <map>
                    <entry key="d1" value-ref="d1"/>
                    <entry key="d2" value-ref="d2"/>
                </map>
            </property>
           <property name="defaultTargetDataSource" ref="d1"/>
        </bean>
     

    Service 中进行切换:

  •  @TargetDataSource(TargetDataSource.DATASOURCE1)
        public boolean saveCustomDictionary(List<String> lines, String url, String customBakUrl) throws IOException, InterruptedException {
            return dataPoolRepository.findAll(pageRequest).getContent();

  • //.....省略代码
        }

  • 问题是  这里调用JPA的fidAll 分页查询  显示 “对象名‘***’无效”....

  • 如图:

  •  

  • 写回答

1条回答 默认 最新

  • 王威振的csdn 2020-11-19 10:32
    关注

    你少了一步吧。

    1. import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

    2. public class DynamicDataSource extends AbstractRoutingDataSource {

    3. @Override

    4. protected Object determineCurrentLookupKey() {

    5. return CustomerContextHolder.getCustomerType();

    6. }

    7.  

     

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 11月22日
  • 已采纳回答 11月14日

悬赏问题

  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题