java多数据源切换

开发中会出现多数据源切换的需求,
方案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();
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值