spring-data-jpa+spring+hibernate+druid配置

参考链接:http://doc.okbase.net/liuyitian/archive/109276.html

http://my.oschina.net/u/1859292/blog/312188


最新公司的web项目需要用到spring-data-jpa作为JPA 的实现框架,同时使用阿里巴巴的开源数据库连接池druid。关于这两种框架的介绍我在这里就不多赘述。直接进入配置页面:


spring的配置:

<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context" 
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx-4.1.xsd 
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-4.2.xsd
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
	http://www.springframework.org/schema/data/jpa
	http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
	"
	xmlns:tx="http://www.springframework.org/schema/tx">


	<!-- 引入druid连接池配置文件 -->
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:druid.properties</value>
			</list>
		</property>
	</bean>

	<!-- 扫描DAO interface包,自动完成DAO注入 添加事务管理 -->
	<jpa:repositories base-package="dao" transaction-manager-ref="transactionManager" entity-manager-factory-ref="entityManagerFactory" />
	
	<!-- Hibernate对Jpa的实现 -->
	<bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
	
	<!-- 定义数据源 使用proxool连接池
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="org.logicalcobwebs.proxool.ProxoolDriver" />
		<property name="url" value="proxool.MyPool"></property>
	</bean> -->
	
	<!-- 定义数据源 使用druid连接池 -->
	
	<bean id="dataSource"
		class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<!-- 初始化连接数量 type:int -->
		<property name="initialSize" value="${druid.initialSize}" />
		<!-- 最大并发数量 type:int -->
		<property name="maxActive" value="${druid.maxActive}" />
		<!-- 最大空闲数量 type:int -->
		<property name="maxIdle" value="${druid.maxIdle}" />
		<!-- 最小空闲数量 type:int -->
		<property name="minIdle" value="${druid.minIdle}" />
		<!-- 配置获取连接等待超时的时间,单位:毫秒 type:long -->
		<property name="maxWait" value="${druid.maxWait}" />
		<!-- 超过时间限制是否回收 type:boolean -->
		<property name="removeAbandoned" value="${druid.removeAbandoned}" />
		<!-- 上述回收超时时间 单位:秒 type:long -->
		<property name="removeAbandonedTimeout" value="${druid.removeAbandonedTimeout}" />
		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}" />
		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}" />
		<!-- 用来检测连接是否有效的sql,要求是一个查询语句 type:sql -->
		<property name="validationQuery" value="${druid.validationQuery}" />
		<!-- 申请连接的时候检测 type:boolean -->
		<property name="testWhileIdle" value="${druid.testWhileIdle}" />
		<!-- 申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能 -->
		<property name="testOnBorrow" value="${druid.testOnBorrow}" />
		<!-- 归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能  -->
		<property name="testOnReturn" value="${druid.testOnReturn}" />
		<!-- 开启PSCache,并且指定每个连接上PSCache的大小 -->
		<property name="poolPreparedStatements" value="${druid.poolPreparedStatements}" />
		<property name="maxPoolPreparedStatementPerConnectionSize" value="${druid.maxPoolPreparedStatementPerConnectionSize}" />
		<!--属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:                 
                监控统计用的filter:stat
                日志用的filter:log4j
               防御SQL注入的filter:wall -->
		<property name="filters" value="${druid.filters}" />
	</bean>
	
	<!-- 定义实体类管理工厂 -->
	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<!-- 注入数据源 -->
		<property name="dataSource" ref="dataSource" />
		<!-- 指定Jpa持久化实现厂商类,这里以Hibernate为例 -->
		<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
		<!-- 指定自动扫描的注解实体类包 -->
		<property name="packagesToScan" value="bean" />
		<property name="jpaProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
				<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
				<prop key="hibernate.hbm2ddl.auto">validate</prop>
				<!-- <prop key="hibernate.connection.username">${jdbc.username}</prop>
				<prop key="hibernate.connection.password">${jdbc.password}</prop> -->
			</props>
		</property>
	</bean>


	<!-- 事务管理器 使用JPA事务管理-->
	<bean id="transactionManager"
		class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>
	
	<!-- 启动对@AspectJ(面向切面)注解的支持 -->
	<aop:aspectj-autoproxy/>
	
	<!-- 事务注解驱动 -->
	<tx:annotation-driven transaction-manager="transactionManager" />
</beans>


spring mvc的配置(默认的路径是WEB -INF下的spring-servlet.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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context" 
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx-4.1.xsd 
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-4.2.xsd
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
	http://www.springframework.org/schema/mvc    
    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
	"
	xmlns:tx="http://www.springframework.org/schema/tx">


	<context:component-scan base-package="dao"/>
	<context:component-scan base-package="service"/>
	<context:component-scan base-package="controller"/>
	<mvc:annotation-driven />
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
	<aop:aspectj-autoproxy/>
	
</beans>


web.xml的配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Web</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 <!-- 配置proxool的配置文件路径
  <context-param>      
    <param-name>proxoolConfigLocation</param-name>      
    <param-value>WEB-INF/proxool.xml</param-value>  
  </context-param>
  proxool连接池监听器
  <listener>      
    <listener-class>org.logicalcobwebs.proxool.configuration.ListenerConfigurator</listener-class> 
  </listener> -->
  
  <!-- 静态文件过滤器 -->
  <filter>
    <filter-name>DruidWebStatFilter</filter-name>
    <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
    <init-param>
      <param-name>exclusions</param-name>
      <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>DruidWebStatFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- druid监控页面servlet -->
  <servlet>
    <servlet-name>DruidStatView</servlet-name>
    <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>   
  </servlet>    
  <servlet-mapping>
    <servlet-name>DruidStatView</servlet-name>
    <url-pattern>/druid/*</url-pattern>
  </servlet-mapping>
  
  <!-- spring监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  
  <!-- spring mvc servlet -->
  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
 <!--  <filter>
    <filter-name>SpringOpenSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>SpringOpenSessionInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping> -->
</web-app>





可以使用Druid数据源和Spring Boot的多数据源支持来实现动态切换MySQL数据源。具体步骤如下: 1. 添加DruidSpring Boot多数据源依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.21</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> ``` 2. 配置Druid数据源 在application.properties文件中添加以下配置: ```properties # 数据源1 spring.datasource.druid.datasource-1.url=jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false spring.datasource.druid.datasource-1.username=root spring.datasource.druid.datasource-1.password=123456 spring.datasource.druid.datasource-1.driver-class-name=com.mysql.cj.jdbc.Driver # 数据源2 spring.datasource.druid.datasource-2.url=jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false spring.datasource.druid.datasource-2.username=root spring.datasource.druid.datasource-2.password=123456 spring.datasource.druid.datasource-2.driver-class-name=com.mysql.cj.jdbc.Driver ``` 3. 配置多数据源 在application.properties文件中添加以下配置: ```properties # 数据源1对应的JPA配置 spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect spring.datasource.druid.datasource-1.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.druid.datasource-1.initial-size=5 spring.datasource.druid.datasource-1.min-idle=5 spring.datasource.druid.datasource-1.max-active=20 spring.datasource.druid.datasource-1.filters=stat,log4j # 数据源2对应的JPA配置 datasource2.jpa.hibernate.ddl-auto=update datasource2.jpa.show-sql=true datasource2.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect spring.datasource.druid.datasource-2.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.druid.datasource-2.initial-size=5 spring.datasource.druid.datasource-2.min-idle=5 spring.datasource.druid.datasource-2.max-active=20 spring.datasource.druid.datasource-2.filters=stat,log4j # 多数据源配置 spring.datasource.dynamic.primary=datasource-1 spring.datasource.dynamic.datasource-1=druid.datasource-1 spring.datasource.dynamic.datasource-2=druid.datasource-2 ``` 4. 编写动态数据源切换代码 在需要使用多数据源的地方,通过以下代码来动态切换数据源: ```java // 获取数据源 DynamicDataSourceContextHolder.setDataSourceKey("datasource-1"); DataSource dataSource = DynamicDataSource.getInstance().getDataSource(); // 使用数据源 JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); List<Map<String, Object>> result = jdbcTemplate.queryForList("select * from user"); // 切换数据源 DynamicDataSourceContextHolder.setDataSourceKey("datasource-2"); dataSource = DynamicDataSource.getInstance().getDataSource(); jdbcTemplate = new JdbcTemplate(dataSource); result = jdbcTemplate.queryForList("select * from user"); ``` 以上就是使用DruidSpring Boot多数据源支持来实现动态切换MySQL数据源的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值