开发中会出现多数据源切换的需求,
方案1:
jdbc方式,建立多个数据源连接
方案2:使用hibernate连接oracle为例,在实体中添加表空间的注解
需要在space1的为当前用户授权访问
方案3:
使用spring的多数据源切换
方案1:
jdbc方式,建立多个数据源连接
private static String driver;
private static String url;
private static String username;
private static String password;
static {
try {
Properties props = new Properties();
InputStream is = ConnectionUtils.class.getClassLoader().getResourceAsStream("tools/db/jdbc/db.properties");
props.load(is);
driver = props.getProperty("driver");
url = props.getProperty("url");
username = props.getProperty("username");
password = props.getProperty("password");
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("", e);
}
}
/**
*
*/
public static Connection openConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
方案2:使用hibernate连接oracle为例,在实体中添加表空间的注解
需要在space1的为当前用户授权访问
grant select on 表空间.表名 to 访问用户的表空间;
@Entity
@Table(name = "T_ORDER", schema = "space1")
public class TOrder implements java.io.Serializable {
......
}
方案3:
使用spring的多数据源切换
<bean name="dataSourceA" class="com.alibaba.druid.pool.DruidDataSource">
</bean>
<bean name="dataSourceB" class="com.alibaba.druid.pool.DruidDataSource">
</bean>
<bean id="dynamicDataSource" class="ps.frank.moreDB.service.dynamic.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry value-ref="dataSourceA" key="dataSourceA"></entry>
<entry value-ref="dataSourceB" key="dataSourceB"></entry>
</map>
</property>
<property name="defaultTargetDataSource" ref="dataSourceA">
</property>
</bean>
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource{
@Override
protected Object determineCurrentLookupKey() {
return DBContextHolder.getDBType();
}
}