`

jeesit 基于springMVC + mybatis配置多数据源的问题

阅读更多

最近需要配置多数据源的问题,根据资料我进行了以下配置,但是运行时总是无法切换数据源
一、项目目录结构

 

二、注解类
 

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface DataSourceInf {
    String value() default DataSource.DATASOURCE_DEFAULT;
}

 

 

三、数据源类

 

public class DataSource {
    /**
     * 读写数据库
     */
    public static final String DATASOURCE_DEFAULT = "dataSource";

    /**
     * 只读数据库
     */
    public static final String DATASOURCE_READ = "dataSource_read";

    /**
     * 只读数据库
     */
    public static final String DATASOURCE_WRITE = "dataSource_write";

}

 

 

四、AOP拦截类

 

@Order(0)
@Aspect
@Component
public class DynamicDataSourceAspect {

    @Around("within(com.thinkgem.jeesite.modules.wql.service..*) && @annotation(db)")
    public Object doBasicProfiling(ProceedingJoinPoint pjp, DataSourceInf db) throws Throwable {
        DynamicDataSource.setDataSource(db.value());
        Object object = null;
        try {
            object = pjp.proceed();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        // 继续执行该方法
        DynamicDataSource.setDefault();
        return object;
    }
}

 

五、

DynamicDataSource.java

 

public class DynamicDataSource extends AbstractRoutingDataSource {
    private  static final ThreadLocal<String> holder = new ThreadLocal<String>();

    public static void setDataSource(String dbType) {
        holder.set(dbType);
    }

    public static void setDefault() {
        holder.set("dataSource");
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return holder.get();
    }
}

 

 

六、配置数据源,jeesit.properties

 

jdbc.type=mysql
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/jeesite?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=admin


#mysql database setting
jdbc2.driver=com.mysql.jdbc.Driver
jdbc2.url=jdbc:mysql://197.2.127.11:3306/test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
jdbc2.username=root
jdbc2.password=admin

#mysql database setting
jdbc3.driver=com.mysql.jdbc.Driver
jdbc3.url=jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=utf-8
jdbc3.username=root
jdbc3.password=admin

 七、配置文件,spring-context.xml

 

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task"
	   xmlns:aop="http://www.springframework.org/schema/aop"
	   xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
	default-lazy-init="true">

	<description>Spring Configuration</description>
	
    <!-- 加载配置属性文件 -->
	<context:property-placeholder ignore-unresolvable="true" location="classpath:jeesite.properties" />
	
	<!-- 加载应用属性实例,可通过  @Value("#{APP_PROP['jdbc.driver']}") String jdbcDriver 方式引用 -->
    <util:properties id="APP_PROP" location="classpath:jeesite.properties" local-override="true"/>
	
	<!-- 使用Annotation自动注册Bean,解决事物失效问题:在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解。  -->
	<context:component-scan base-package="com.thinkgem.jeesite"><!-- base-package 如果多个,用“,”分隔 -->
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>
	
 	<!-- MyBatis begin -->
	<bean id="dynamicDataSource" class="com.thinkgem.jeesite.common.db.DynamicDataSource">
		<property name="defaultTargetDataSource" ref="dataSource"></property>
		<property name="targetDataSources">
			<map key-type="java.lang.String">
				<entry value-ref="dataSource" key="dataSource"></entry>
				<entry value-ref="dataSource_read" key="dataSource_read"></entry>
				<entry value-ref="dataSource_write" key="dataSource_write"></entry>
			</map>
		</property>
	</bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dynamicDataSource"/>
        <property name="typeAliasesPackage" value="com.thinkgem.jeesite"/>
        <property name="typeAliasesSuperType" value="com.thinkgem.jeesite.common.persistence.BaseEntity"/>
        <property name="mapperLocations" value="classpath:/mappings/**/*.xml"/>
		<property name="configLocation" value="classpath:/mybatis-config.xml"></property>
    </bean>
    
    <!-- 扫描basePackage下所有以@MyBatisDao注解的接口 -->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <property name="basePackage" value="com.thinkgem.jeesite"/>
        <property name="annotationClass" value="com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao"/>
    </bean>
    
    <!-- 定义事务 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dynamicDataSource" />
	</bean>
	
	<!-- 配置 Annotation 驱动,扫描@Transactional注解的类定义事务  -->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
    <!-- MyBatis end -->
    
	<!-- 配置 JSR303 Bean Validator 定义 -->
	<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

	<!-- 缓存配置 -->
	<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
		<property name="configLocation" value="classpath:${ehcache.configFile}" />
	</bean>
	
	<!-- 计划任务配置,用 @Service @Lazy(false)标注类,用@Scheduled(cron = "0 0 2 * * ?")标注方法 -->
    <task:executor id="executor" pool-size="10"/> <task:scheduler id="scheduler" pool-size="10"/>
    <task:annotation-driven scheduler="scheduler" executor="executor" proxy-target-class="true"/>
    
	<!-- 数据源配置, 使用 BoneCP 数据库连接池 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> 
	    <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->
	    <property name="driverClassName" value="${jdbc.driver}" />
	    
		<!-- 基本属性 url、user、password -->
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		
		<!-- 配置初始化大小、最小、最大 -->
		<property name="initialSize" value="${jdbc.pool.init}" />
		<property name="minIdle" value="${jdbc.pool.minIdle}" /> 
		<property name="maxActive" value="${jdbc.pool.maxActive}" />
		
		<!-- 配置获取连接等待超时的时间 -->
		<property name="maxWait" value="60000" />
		
		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="60000" />
		
		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="300000" />
		
		<property name="validationQuery" value="${jdbc.testSql}" />
		<property name="testWhileIdle" value="true" />
		<property name="testOnBorrow" value="false" />
		<property name="testOnReturn" value="false" />
		
		<!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用)
		<property name="poolPreparedStatements" value="true" />
		<property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> -->
		
		<!-- 配置监控统计拦截的filters -->
	    <property name="filters" value="stat" /> 
	</bean>


	<!-- 数据源配置, 使用 BoneCP 数据库连接池 -->
	<bean id="dataSource_read" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
		<!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->
		<property name="driverClassName" value="${jdbc2.driver}" />

		<!-- 基本属性 url、user、password -->
		<property name="url" value="${jdbc2.url}" />
		<property name="username" value="${jdbc2.username}" />
		<property name="password" value="${jdbc2.password}" />

		<!-- 配置初始化大小、最小、最大 -->
		<property name="initialSize" value="${jdbc.pool.init}" />
		<property name="minIdle" value="${jdbc.pool.minIdle}" />
		<property name="maxActive" value="${jdbc.pool.maxActive}" />

		<!-- 配置获取连接等待超时的时间 -->
		<property name="maxWait" value="60000" />

		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="60000" />

		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="300000" />

		<property name="validationQuery" value="${jdbc.testSql}" />
		<property name="testWhileIdle" value="true" />
		<property name="testOnBorrow" value="false" />
		<property name="testOnReturn" value="false" />

		<!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用)
		<property name="poolPreparedStatements" value="true" />
		<property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> -->

		<!-- 配置监控统计拦截的filters -->
		<property name="filters" value="stat" />
	</bean>

	<!-- 数据源配置, 使用 BoneCP 数据库连接池 -->
	<bean id="dataSource_write" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
		<!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->
		<property name="driverClassName" value="${jdbc3.driver}" />

		<!-- 基本属性 url、user、password -->
		<property name="url" value="${jdbc3.url}" />
		<property name="username" value="${jdbc3.username}" />
		<property name="password" value="${jdbc3.password}" />

		<!-- 配置初始化大小、最小、最大 -->
		<property name="initialSize" value="${jdbc.pool.init}" />
		<property name="minIdle" value="${jdbc.pool.minIdle}" />
		<property name="maxActive" value="${jdbc.pool.maxActive}" />

		<!-- 配置获取连接等待超时的时间 -->
		<property name="maxWait" value="60000" />

		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="60000" />

		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="300000" />

		<property name="validationQuery" value="${jdbc.testSql}" />
		<property name="testWhileIdle" value="true" />
		<property name="testOnBorrow" value="false" />
		<property name="testOnReturn" value="false" />

		<!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用)
		<property name="poolPreparedStatements" value="true" />
		<property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> -->

		<!-- 配置监控统计拦截的filters -->
		<property name="filters" value="stat" />
	</bean>

	<!-- 配置AOP -->
	<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
	
	<!-- 数据源配置, 使用应用服务器的数据库连接池 
	<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/jeesite" />-->

	<!-- 数据源配置, 不使用连接池 
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
	</bean>-->
	
</beans>

 

 

 

 

 八,测试类  TUserService.java

 

@Service
@Transactional(readOnly = true)
public class TUserService extends CrudService<TUserDao, TUser> {
	@Autowired
	TUserDao tUserDao;

	public TUser get(String id) {
		return super.get(id);
	}
	
	public List<TUser> findList(TUser tUser) {
		return super.findList(tUser);
	}

	@DataSourceInf(DataSource.DATASOURCE_READ)
	public List<TUser> getAllList() {
		//DynamicDataSource.setDataSource(DataSource.DATASOURCE_READ);
		List list = tUserDao.getAllList();

		System.out.println("<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>"+list.toString());
		return list;
	}
	
	public Page<TUser> findPage(Page<TUser> page, TUser tUser) {
		return super.findPage(page, tUser);
	}
	
	@Transactional(readOnly = false)
	public void save(TUser tUser) {
		super.save(tUser);
	}
	
	@Transactional(readOnly = false)
	public void delete(TUser tUser) {
		super.delete(tUser);
	}
	
}

 

 

运行结果:

错误信息:
### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'jeesite.t_user' doesn't exist
### The error may exist in file [E:\soft\jeesite-master\target\jeesite\WEB-INF\classes\mappings\modules\wql\TUserDao.xml]
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: SELECT a.id AS "id", a.user_name AS "userName", a.password AS "password", a.role_id AS "roleId", a.true_name AS "trueName", a.create_time AS "createTime", a.modify_time AS "modifyTime" FROM t_user a where 1=1
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'jeesite.t_user' doesn't exist
; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'jeesite.t_user' doesn't exist

 

有以下两个问题:

问题1、上面在service层不管是以注解的形式,还是以(

DynamicDataSource.setDataSource(DataSource.DATASOURCE_READ)

)的形式,都报上面的错误,找不到表,这应该就是没有正确的切换数据源,不知道问题具体出在哪里?经过测试,如果控制在controller中(以

DynamicDataSource.setDataSource(DataSource.DATASOURCE_READ)

)的形式进行切换是可以的。

问题2、我又换了一种方式,如果在DAO中进行注解,则根本无法进入AOP拦截中,配置如下

(1)、DAO类  TUserDao.java

 

@MyBatisDao
@DataSourceInf(DataSource.DATASOURCE_READ)
public interface TUserDao extends CrudDao<TUser> {
	@DataSourceInf(DataSource.DATASOURCE_READ)
	public List<TUser> getAllList();
}

 (2)、AOP拦截类  DynamicDataSourceAspect.java 

该类只修改了需要拦截的文件路径

 

@Around("within(com.thinkgem.jeesite.modules.wql.dao..*) && @annotation(db)")

 修改完毕后,运行后则根本没有进入AOP拦截类,是不是因为DAO是一个接口?

 

 

求大神解答,谢谢。酷

 

  • 大小: 28.2 KB
分享到:
评论

相关推荐

    Java基于Spring+SpringMVC+MyBatis实现的学生信息管理系统源码.zip

    Java基于Spring+SpringMVC+MyBatis实现的学生信息管理系统源码,SSM+Vue的学生管理系统。 Java基于Spring+SpringMVC+MyBatis实现的学生信息管理系统源码,SSM+Vue的学生管理系统。 Java基于Spring+SpringMVC+...

    SSM(Spring+SpringMVC+MyBatis)多数据源配置框架

    9. **安全性**:多数据源配置也可能涉及安全问题,如权限控制和数据隔离,需要确保不同数据源间的访问控制得到妥善处理。 综上所述,SSM多数据源配置框架是一种强大的工具,它为企业级应用提供了灵活的数据处理能力...

    基于Spring+SpringMVC+Mybatis架构的博客系统.zip

    基于Spring+SpringMVC+Mybatis架构的博客系统:博客管理、图表数据、日志分析、访问记录、图库管理、资源管理、友链通知等。良好的页面预加载,无限滚动加载,文章置顶,博主推荐等。提供 用户端+管理端 的整套系统...

    完善的Spring+SpringMVC+Mybatis+easyUI后台管理系统(RESTful API+redis).zip

    完善的Spring+SpringMVC+Mybatis+easyUI后台管理系统(RESTful API+redis).zip 完善的Spring+SpringMVC+Mybatis+easyUI后台管理系统(RESTful API+redis).zip 完善的Spring+SpringMVC+Mybatis+easyUI后台管理系统...

    基于SpringBoot+Spring+SpringMvc+Mybatis+Shiro+Redis 开发单点登录管理系统源码

    基于 SpringBoot + Spring + SpringMvc + Mybatis + Shiro+ Redis 开发单点登录管理系统 基于 SpringBoot + Spring + SpringMvc + Mybatis + Shiro+ Redis 开发单点登录管理系统 基于 SpringBoot + Spring + ...

    基于SSM(Spring+SpringMVC+Mybatis)的新闻管理系统源码+数据库.zip

    基于SSM(Spring+SpringMVC+Mybatis)的新闻管理系统源码+数据库.zip 基于SSM(Spring+SpringMVC+Mybatis)的新闻管理系统源码+数据库.zip 基于SSM(Spring+SpringMVC+Mybatis)的新闻管理系统源码+数据库.zip 基于SSM...

    图书管理系统SpringMvc+mybatis

    《图书管理系统SpringMvc+Mybatis实现详解》 在IT领域,构建高效、稳定的软件系统是至关重要的。本项目“图书管理系统”就是这样一个实例,它利用了SpringMvc和Mybatis两大主流框架,为图书管理提供了全面的解决...

    毕设项目:基于SpringMVC+MyBatis开发学生管理系统.zip

    毕设项目:基于SpringMVC+MyBatis开发学生管理系统 毕设项目:基于SpringMVC+MyBatis开发学生管理系统 毕设项目:基于SpringMVC+MyBatis开发学生管理系统 毕设项目:基于SpringMVC+MyBatis开发学生管理系统 毕设项目...

    基于SpringMVC+Spring+MyBatis个人技术博客系统源码.zip

    基于SpringMVC+Spring+MyBatis个人技术博客系统源码.zip 完整代码,可运行 项目描述 基于SSM实现的一个个人博客系统,适合初学SSM和个人博客制作的同学学习。有了这个源码,直接买了阿里云或腾讯服务器,就可以部署...

    SpringMVC+Mybatis demo

    在"SpringMVC+Mybatis demo"的Service端,开发者已经实现了基于SpringMVC和MyBatis的业务逻辑。后续的客户端可能涉及视图层的展示,例如使用JSP或Thymeleaf等技术来渲染数据,以及Controller层的进一步处理,如处理...

    基于springMVC+mybatis+easyui的留言板源码

    《构建基于SpringMVC+MyBatis+EasyUI的留言板系统》 在现代Web开发中,构建一个功能完善的留言板系统是常见的需求。本资源提供了一个简单的实现案例,它基于SpringMVC、MyBatis和EasyUI这三个流行的技术框架,旨在...

    本科毕设-课设-基于SpringMVC+MyBatis开发学生管理系统.zip

    本科毕设-课设-基于SpringMVC+MyBatis开发学生管理系统.zip本科毕设-课设-基于SpringMVC+MyBatis开发学生管理系统.zip本科毕设-课设-基于SpringMVC+MyBatis开发学生管理系统.zip本科毕设-课设-基于SpringMVC+MyBatis...

    基于SpringMVC + MyBatis实现的小说系统.zip

    这是一款基于SpringMVC + MyBatis实现的小说系统, 目前只有wap端。 前端采用vue的框架cube-ui, 采用前后端分离的结构,系统中针对数据接口安全做了一定的限制, 很大程度上保证了数据的安全性。 这是一款基于...

    基于SpringMVC+Spring+MyBatis+Maven项目案例.zip

    基于SpringMVC+Spring+MyBatis+Maven项目案例 基于SpringMVC+Spring+MyBatis+Maven项目案例 基于SpringMVC+Spring+MyBatis+Maven项目案例 基于SpringMVC+Spring+MyBatis+Maven项目案例 基于SpringMVC+Spring+MyBatis...

    spring+springMVC+mybatis+quartz动态定时任务创建

    总结来说,"spring+springMVC+mybatis+quartz动态定时任务创建"这个技术栈利用Spring的全面性、Spring MVC的Web处理能力、MyBatis的数据访问效率以及Quartz的定时任务管理,构建出一个能够灵活应对各种定时需求的...

    基于SpringMVC+Spring+MyBatis+Maven项目案例源码+数据库.zip

    【资源说明】 1、该资源包括项目的全部源码,下载可以直接使用! 2、本项目适合作为计算机、数学、电子信息等专业的课程设计、期末大作业和毕设项目,作为参考资料学习...基于SpringMVC+Spring+MyBatis+Maven项目案例源

    maven+springMVC+mybatis+velocity+mysql+junit项目框架搭建

    本项目框架“maven+springMVC+mybatis+velocity+mysql+junit”提供了一种高效、灵活且可维护的解决方案。以下将详细讲解这些组件及其作用。 1. Maven: Maven是一个项目管理工具,用于构建、依赖管理和项目信息...

    基于spring+springMvc+mybatis 开发的企业门户网站

    基于spring+springMvc+mybatis 开发的企业门户网站基于spring+springMvc+mybatis 开发的企业门户网站基于spring+springMvc+mybatis 开发的企业门户网站基于spring+springMvc+mybatis 开发的企业门户网站基于spring+...

    Spring+SpringMVC+Mybatis框架整合例子(SSM) 下载

    4. 配置Mybatis:创建mybatis的全局配置文件,mybatis-config.xml,配置数据源、SqlSessionFactory等,以及Mapper的XML配置文件。 5. 编写DAO层:定义Mapper接口,编写对应的Mapper XML文件,实现SQL语句。 6. 业务...

    毕设项目-基于Spring + SpringMvc + MyBatis搭建的学生信息管理系统源码.zip

    毕设项目-基于Spring + SpringMvc + MyBatis搭建的学生信息管理系统源码.zip毕设项目-基于Spring + SpringMvc + MyBatis搭建的学生信息管理系统源码.zip毕设项目-基于Spring + SpringMvc + MyBatis搭建的学生信息...

Global site tag (gtag.js) - Google Analytics