在一个应用程序中,我们有三个数据库服务器
1. db1
2. db2
3.db3
我们为上述连接配置了jndi
如果在db1中没有连接,那么从db2应用程序将建立连接,如果在db2中没有连接,应用程序将在db2.how中建立连接以实现这个spring jdbc模板。服务器的细节
tomcat 8.0 server,spring 4.0,oracle
答案 0 :(得分:0)
这是您可以参考此来源的问题示例。
application.properties
spring.ds_items.driverClassName=org.postgresql.Driver
spring.ds_items.url=jdbc:postgresql://srv0/test
spring.ds_items.username=test0
spring.ds_items.password=test0
spring.ds_users.driverClassName=org.postgresql.Driver
spring.ds_users.url=jdbc:postgresql://srv1/test
spring.ds_users.username=test1
spring.ds_users.password=test1
DatabaseItemsConfig.java
import javax.sql.DataSource;
@Configuration
@ConfigurationProperties(name = "spring.ds_items")
public class DatabaseItemsConfig extends TomcatDataSourceConfiguration {
@Bean(name = "dsItems")
public DataSource dataSource() {
return super.dataSource();
}
@Bean(name = "jdbcItems")
public JdbcTemplate jdbcTemplate(DataSource dsItems) {
return new JdbcTemplate(dsItems);
}
}
DatabaseUsersConfig.java
import javax.sql.DataSource;
@Configuration
@ConfigurationProperties(name = "spring.ds_users")
public class DatabaseUsersConfig extends TomcatDataSourceConfiguration {
@Bean(name = "dsUsers")
public DataSource dataSource() {
return super.dataSource();
}
@Bean(name = "jdbcUsers")
public JdbcTemplate jdbcTemplate(DataSource dsUsers) {
return new JdbcTemplate(dsUsers);
}
}
ItemRepository.java
import java.sql.ResultSet;
import java.sql.SQLException;
@Repository
public class ItemRepository {
protected final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
@Qualifier("jdbcItems")
protected JdbcTemplate jdbc;
public Item getItem(long id) {
return jdbc.queryForObject("SELECT * FROM sb_item WHERE id=?", itemMapper, id);
}
private static final RowMapper<Item> itemMapper = new RowMapper<Item>() {
public Item mapRow(ResultSet rs, int rowNum) throws SQLException {
Item item = new Item(rs.getLong("id"), rs.getString("title"));
item.price = rs.getDouble("id");
return item;
}
};
}
UserRepository.java
import java.sql.ResultSet;
import java.sql.SQLException;
@Repository
public class UserRepository {
protected final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
@Qualifier("jdbcUsers")
protected JdbcTemplate jdbc;
public User getUser(long id) {
return jdbc.queryForObject("SELECT * FROM sb_user WHERE id=?", userMapper, id);
}
private static final RowMapper<User> userMapper = new RowMapper<User>() {
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User(rs.getLong("id"), rs.getString("name"));
user.alias = rs.getString("alias");
return user;
}
};
}