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

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 luckysheet
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥50 大二 微机原理 课程design 有偿