Spring3 Annotation + Hibernate3-jpa2.0 + CGLIB + 多数据源(动态数据源)

本文主要是介绍Spring3 Annotation + Hibernate3-jpa2.0 + CGLIB + 多数据源(动态数据源),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、定义一个测试用Entity。 
Java代码   收藏代码
  1. @Entity  
  2. public class Person implements Serializable {  
  3.     private static final long serialVersionUID = 1L;  
  4.   
  5.     @Id @GeneratedValue @Column(name = "id")  
  6.     private Integer id;  
  7.   
  8.     @Column(name = "last_name")  
  9.     private String lastName;  
  10.   
  11.     @Column(name = "first_name")  
  12.     private String firstName;  
  13.   
  14.     public String getFirstName(){return firstName;}  
  15.   
  16.     public void setFirstName(String firstName){this.firstName = firstName;}  
  17.   
  18.     public String getLastName(){return lastName;}  
  19.   
  20.     public void setLastName(String lastName){this.lastName = lastName;  }  
  21.   
  22.     public Integer getId(){return id;}  
  23.   
  24.     public void setId(Integer id){this.id = id;}  
  25. }  

二、applicationContext.xml与META-INF/persistent.xml 
Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.  xmlns:tx="http://www.springframework.org/schema/tx"  
  5.  xmlns:context="http://www.springframework.org/schema/context"  
  6.  xmlns:aop="http://www.springframework.org/schema/aop"  
  7.  xsi:schemaLocation="http://www.springframework.org/schema/beans  
  8.   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  9.   http://www.springframework.org/schema/tx  
  10.   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
  11.   http://www.springframework.org/schema/context  
  12.   http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  13.   http://www.springframework.org/schema/aop  
  14.   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">  
  15.   
  16.       <!--指定spring容器自动扫描的包:@Repository...-->  
  17.     <context:component-scan base-package="com.logcd.test,com.logcd.dao,com.logcd.service"/>   
  18.       <!--使用CGLIB代理-->  
  19.     <aop:aspectj-autoproxy proxy-target-class="true"/>  
  20.   
  21.     <bean  
  22.        class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>  
  23.   
  24.     <bean id="ds1"   
  25.       class="org.springframework.jdbc.datasource.DriverManagerDataSource">   
  26.       <property name="driverClassName" value="com.mysql.jdbc.Driver"/>   
  27.       <property name="url" value="jdbc:mysql://localhost:3306/springapp"/>   
  28.       <property name="username" value="root"/>   
  29.       <property name="password" value="root"/>   
  30.     </bean>   
  31.   
  32.     <bean id="ds2"   
  33.       class="org.springframework.jdbc.datasource.DriverManagerDataSource">   
  34.       <property name="driverClassName" value="com.mysql.jdbc.Driver"/>   
  35.       <property name="url" value="jdbc:mysql://localhost:3306/test"/>   
  36.       <property name="username" value="root"/>   
  37.       <property name="password" value="root"/>   
  38.     </bean>   
  39.       <!--动态选择数据源-->  
  40.     <bean id="dataSource" class="com.logcd.util.DynamicDataSource">  
  41.         <property name="targetDataSources">  
  42.             <map key-type="java.lang.String">  
  43.                 <entry key="1" value-ref="ds1"/>  
  44.                 <entry key="2" value-ref="ds2"/>  
  45.             </map>  
  46.         </property>  
  47.         <property name="defaultTargetDataSource" ref="ds1"/>  
  48.     </bean>  
  49.   
  50.     <bean id="entityManagerFactory"  
  51.         class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"  
  52.         destroy-method="destroy">  
  53.         <property name="dataSource" ref="dataSource" />  
  54.         <property name="jpaVendorAdapter">  
  55.             <bean  
  56.                 class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">  
  57.                 <property name="database" value="MYSQL"/>  
  58.                 <property name="generateDdl" value="true"/>  
  59.                 <property name="showSql" value="true"/>  
  60.             </bean>  
  61.         </property>  
  62.     </bean>  
  63.       
  64.     <bean id="transactionManager"   
  65.         class="org.springframework.orm.jpa.JpaTransactionManager">  
  66.         <property name="dataSource" ref="dataSource"/>  
  67.         <property name="entityManagerFactory"  
  68.             ref="entityManagerFactory"/>  
  69.     </bean>  
  70.       
  71.     <tx:annotation-driven transaction-manager="transactionManager"/>  
  72.   
  73. </beans>  

Xml代码   收藏代码
  1. <persistence xmlns="http://java.sun.com/xml/ns/persistence"   
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  3. xsi:schemaLocation="http://java.sun.com/xml/ns/persistencehttp://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"   
  4. version="1.0">   
  5.   
  6.     <!--  local or global(JTA) transaction -->  
  7.     <persistence-unit name="SpringJpa" transaction-type="RESOURCE_LOCAL"/>  
  8.   
  9. </persistence>   

三、在Spring 2.0.1中引入了AbstractRoutingDataSource, 该类充当了DataSource的路由中介, 能有在运行时, 根据某种key值来动态切换到真正的DataSource上, 同时对于不支持事务隔离级别的JTA事务来说, Spring还提供了另外一个类IsolationLevelDataSourceRouter来处理。IsolationLevelDataSourceRouter: 会根据当前Spring受管事务启用的隔离级别来选定合适的DataSource数据源。 
Java代码   收藏代码
  1. import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;  
  2.   
  3. public class DynamicDataSource extends AbstractRoutingDataSource {  
  4.   
  5.     @Override  
  6.     protected Object determineCurrentLookupKey() {  
  7.           
  8.         return DbContextHolder.getDbType();  
  9.           
  10.     }  
  11.   
  12. }  

Java代码   收藏代码
  1. public class DbContextHolder {  
  2.       
  3.     private static final ThreadLocal<Object> contextHolder = new ThreadLocal<Object>();  
  4.       
  5.     public static void setDbType(Object dbType) {  
  6.         contextHolder.set(dbType);  
  7.     }  
  8.       
  9.     public static String getDbType() {  
  10.         return (String) contextHolder.get();  
  11.     }  
  12.       
  13.     public static void clearDbType() {  
  14.         contextHolder.remove();  
  15.     }    
  16.       
  17. }  

四、数据访问Dao 
Java代码   收藏代码
  1. import java.io.Serializable;  
  2. import java.util.List;  
  3.   
  4. import javax.persistence.EntityManager;  
  5. import javax.persistence.PersistenceContext;  
  6. import javax.persistence.Query;  
  7.   
  8. import org.springframework.stereotype.Repository;  
  9. import org.springframework.transaction.annotation.Transactional;  
  10.   
  11. @Repository  
  12. @Transactional  
  13. public class BaseDao<T>{  
  14.   
  15.     @PersistenceContext  
  16.     protected EntityManager em;   
  17.   
  18.     public void persist(T t) {  
  19.         em.persist(t);  
  20.     }  
  21.   
  22.     @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)  
  23.       public T save(T t) {  
  24.         return em.merge(t);  
  25.     }  
  26.   
  27.     public void delete(T t) {  
  28.         em.remove(t);  
  29.     }  
  30.   
  31.     @Transactional(readOnly = true, isolation=Isolation.READ_COMMITTED)  
  32.     public T find(Class<T> clazz, Serializable id) {  
  33.         return em.getReference(clazz, id);  
  34.     }  
  35.       
  36.     @SuppressWarnings("unchecked")  
  37.     public List<T> find(String jpql) {  
  38.         return em.createQuery(jpql).getResultList();  
  39.     }  
  40.       
  41.       
  42.     @SuppressWarnings("unchecked")  
  43.     public List<T> find(String jpql, Object param) {  
  44.         return em.createQuery(jpql).setParameter(1, param).getResultList();  
  45.     }  
  46.   
  47.     @SuppressWarnings("unchecked")  
  48.     public List<T> find(String jpql, Object[] param) {  
  49.         Query query = em.createQuery(jpql);  
  50.         for (int i = 1; i <= param.length; i++) {  
  51.             query.setParameter(i, param[i - 1]);  
  52.         }  
  53.         return query.getResultList();  
  54.     }  
  55.   
  56.     public int findTotalCount(String jpql) {  
  57.         return ((Long) em.createQuery(jpql).getSingleResult()).intValue();  
  58.     }  
  59.       
  60. }  

五、测试 
Java代码   收藏代码
  1. import static org.junit.Assert.assertEquals;  
  2. import static org.junit.Assert.assertNotNull;  
  3.   
  4. import java.util.List;  
  5.   
  6. import org.junit.Ignore;  
  7. import org.junit.Test;  
  8. import org.junit.runner.RunWith;  
  9. import org.springframework.beans.factory.annotation.Autowired;  
  10. import org.springframework.test.context.ContextConfiguration;  
  11. import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;  
  12. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  13.   
  14. import com.logcd.dao.BaseDao;  
  15. import com.logcd.entity.Person;  
  16. import com.logcd.util.DbContextHolder;  
  17.   
  18. @RunWith(SpringJUnit4ClassRunner.class)  
  19. @ContextConfiguration("classpath:applicationContext.xml")  
  20. public class TestBaseDao extends AbstractJUnit4SpringContextTests{  
  21.   
  22.     @Autowired  
  23.     private BaseDao<Person> baseDao;  
  24.   
  25.     @Test  
  26.     public void findPersonById(){  
  27.         List<Person> persons =  
  28.             baseDao.find("from Person a where a.id = ?"new Integer(1));  
  29.         assertNotNull(persons);  
  30.         assertEquals(persons.size(), 1);  
  31.   
  32.         for(Person person: persons){  
  33.             System.out.println(person.getLastName()+" "+person.getFirstName());  
  34.         }  
  35.     }  
  36.       
  37.     @Test  
  38.     public void savePerson(){  
  39.         DbContextHolder.setDbType("2");  
  40.   
  41.         Person  person = new Person();  
  42.         person.setFirstName("Bella");  
  43.         person.setLastName("Edward");  
  44.         person = baseDao.save(person);  
  45.         System.out.println(person.getId());  
  46.           
  47.         DbContextHolder.clearDbType();  
  48.   
  49.     }  
  50.       
  51.     @Ignore  
  52.     public void deletePerson(){  
  53.         baseDao.delete(baseDao.find(Person.classnew Integer(7)));  
  54.     }  
  55.       
  56. }  

六、关于Spring-AOP: JDK代理和CGLIB代理 
1、如果目标对象实现了接口,默认会采用JDK的动态代理机制实现AOP 
2、如果目标对象实现了接口,可以强制使用CGLIB实现AOP 
3、如果目标对象没有实现接口,必须使用CGLIB生成代理,spring会自动在CGLIB和JDK动态代理之间切换 
4、如何强制使用CGLIB生成代理? 
(1)添加CGLIB库,SPRING_HOME/lib/cglib/*.jar 
(2)在spring的配置文件中加入:<aop:aspectj-autoproxy proxy-target-class="true"/> 
5、JDK代理和CGLIB代理的区别? 
(1)JDK代理只能对实现了接口的类生成代理,而不能针对类 
(2)CGLIB是针对类实现代理的,主要对指定的类生成一个子类,并覆盖其中的方法,因为是继承,所以不能使用final来修饰类或方法 
七、关于IsolationLevelDataSourceRouter 
public class IsolationLevelDataSourceRouterextends AbstractRoutingDataSourceDataSource that routes to one of various target DataSources based on the current transaction isolation level. The target DataSources need to be configured with the isolation level name as key, as defined on the TransactionDefinition interface. 

This is particularly useful in combination with JTA transaction management (typically through Spring's JtaTransactionManager). Standard JTA does not support transaction-specific isolation levels. Some JTA providers support isolation levels as a vendor-specific extension (e.g. WebLogic), which is the preferred way of addressing this. As alternative (e.g. on WebSphere), the target database can be represented through multiple JNDI DataSources, each configured with a different isolation level (for the entire DataSource). The present DataSource router allows to transparently switch to the appropriate DataSource based on the current transaction's isolation level. 

The configuration can for example look like this, assuming that the target DataSources are defined as individual Spring beans with names "myRepeatableReadDataSource", "mySerializableDataSource" and "myDefaultDataSource": 

Xml代码   收藏代码
  1. <bean id="dataSourceRouter" class="org.springframework.jdbc.datasource.lookup.IsolationLevelDataSourceRouter">  
  2.   <property name="targetDataSources">  
  3.     <map>  
  4.       <entry key="ISOLATION_REPEATABLE_READ" value-ref="myRepeatableReadDataSource"/>  
  5.       <entry key="ISOLATION_SERIALIZABLE" value-ref="mySerializableDataSource"/>  
  6.     </map>  
  7.   </property>  
  8.   <property name="defaultTargetDataSource" ref="myDefaultDataSource"/>  
  9. </bean>  
Alternatively, the keyed values can also be data source names, to be resolved through a DataSourceLookup: by default, JNDI names for a standard JNDI lookup. This allows for a single concise definition without the need for separate DataSource bean definitions. 
Xml代码   收藏代码
  1. <bean id="dataSourceRouter" class="org.springframework.jdbc.datasource.lookup.IsolationLevelDataSourceRouter">  
  2.   <property name="targetDataSources">  
  3.     <map>  
  4.       <entry key="ISOLATION_REPEATABLE_READ" value="java:comp/env/jdbc/myrrds"/>  
  5.       <entry key="ISOLATION_SERIALIZABLE" value="java:comp/env/jdbc/myserds"/>  
  6.     </map>  
  7.   </property>  
  8.   <property name="defaultTargetDataSource" value="java:comp/env/jdbc/mydefds"/>  
  9. </bean>  
Note: If you are using this router in combination with Spring's JtaTransactionManager, don't forget to switch the "allowCustomIsolationLevels" flag to "true". (By default, JtaTransactionManager will only accept a default isolation level because of the lack of isolation level support in standard JTA itself.) 
Xml代码   收藏代码
  1. <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">  
  2.   <property name="allowCustomIsolationLevels" value="true"/>  
  3. </bean>  

这篇关于Spring3 Annotation + Hibernate3-jpa2.0 + CGLIB + 多数据源(动态数据源)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1079763

相关文章

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件