Thursday 18 September 2014

Multiple DataSources with Hibernate - Approach 2

The later versions spring2.0.1 support configure multiple data sources, different data sources and can be loaded dynamically at run time. Can be achieved through inheritance AbstractRoutingDataSource dynamic conversion of multiple data sources. Do project is the need to access the data source, each data source table structure is the same, it requires changes in the data source is transparent for coders, that is to say the same SQL statement that operate in different circumstances The database is not the same. The specific configuration is as follows: You first need to write a static control key class:

      package cn.com.xinli.ccp.dynamicds; 
  
    public   class DataSourceMap { 
     public   static   final String Admin = "Admin"; 
     public   static   final String Yxh = "Yxh"; 
  } 

This class when in use as a data source flag. Second, the establishment of a class to get and set the context:

      public   class CustomerContextHolder { 
         private   static   final ThreadLocal contextHolder = 
                                new ThreadLocal (); 

      public   static   void setCustomerType (String customerType) { 
            contextHolder.set (customerType); 
       } 
      
      public   static String getCustomerType () { 
        return  (String) contextHolder.get (); 
       } 

      public   static   void clearCustomerType () { 
          contextHolder.remove (); 
        }    
    }

This is mainly responsible for setting the context and the context. Third, the establishment of a dynamic data source class, class must inherit AbstractRoutingDataSource

No comments:

Post a Comment