【Spring Boot 27】Springboot配置两个数据库(附代码+源码分析)

import org.slf4j.LoggerFactory;

import com.alibaba.druid.pool.DruidDataSource;

public class JDBCUtils {

private final static Logger log = LoggerFactory.getLogger(JDBCUtils.class);

/**

  • 定义数据源

*/

private static DataSource ds;

/**

  • 定义数据库连接配置

*/

static {

try {

/**

  • 加载配置文件

*/

DruidDataSource dataSource = new DruidDataSource();

dataSource.setDriverClassName(“org.postgresql.Driver”);

dataSource.setUrl(“jdbc:postgresql://127.0.0.1:5432/test”);

dataSource.setUsername(“postgres”);

dataSource.setPassword(“123456”);

ds = dataSource;

} catch (Exception e) {

log.error(“create connection pool error,errorMessage:{}”, e);

}

}

/**

  • 获取数据源

  • @return 返回数据源

*/

public static DataSource getDataSource(){

return ds;

}

/**

  • 获取连接对象

  • @return 返回连接对象

  • @throws SQLException 抛出的编译异常

*/

public static Connection getConn() throws SQLException {

return ds.getConnection();

}

/**

  • 关闭连接

  • @param stmt sql执行对象

  • @param conn 数据库连接对象

*/

public static void close(Statement stmt, Connection conn){

if(stmt != null){

try {

stmt.close();

} catch (SQLException e) {

log.error(“close error,errorMessage:{}”, e);

}

}

if(conn != null){

try {

conn.close();

} catch (SQLException e) {

log.error(“close error,errorMessage:{}”, e);

}

}

}

/**

  • 关闭资源的重载方法

  • @param rs 处理结果集的对象

  • @param stmt 执行sql语句的对象

  • @param conn 连接数据库的对象

*/

public static void close(ResultSet rs, Statement stmt, Connection conn){

if(rs != null){

try {

rs.close();

} catch (SQLException e) {

log.error(“close error,errorMessage:{}”, e);

}

}

if(stmt != null){

try {

stmt.close();

} catch (SQLException e) {

log.error(“close error,errorMessage:{}”, e);

}

}

if(conn != null){

try {

conn.close();

} catch (SQLException e) {

log.error(“close error,errorMessage:{}”, e);

}

}

}

}

二、jdbcTemplate.queryForList源码初探


public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {

public JdbcTemplate(DataSource dataSource) {

setDataSource(dataSource);

afterPropertiesSet();

}

@Override

public List<Map<String, Object>> queryForList(String sql) throws DataAccessException {

return query(sql, getColumnMapRowMapper());

}

@Override

public List query(String sql, RowMapper rowMapper) throws DataAccessException {

return result(query(sql, new RowMapperResultSetExtractor<>(rowMapper)));

}

@Override

@Nullable

public T query(final String sql, final ResultSetExtractor rse) throws DataAccessException {

Assert.notNull(sql, “SQL must not be null”);

Assert.notNull(rse, “ResultSetExtractor must not be null”);

if (logger.isDebugEnabled()) {

logger.debug(“Executing SQL query [” + sql + “]”);

}

/**

  • Callback to execute the query.

*/

class QueryStatementCallback implements StatementCallback, SqlProvider {

@Override

@Nullable

public T doInStatement(Statement stmt) throws SQLException {

ResultSet rs = null;

try {

rs = stmt.executeQuery(sql);

return rse.extractData(rs);

}

finally {

JdbcUtils.closeResultSet(rs);

}

}

@Override

public String getSql() {

return sql;

}

}

return execute(new QueryStatementCallback());

}

@Override

@Nullable

public T execute(StatementCallback action) throws DataAccessException {

Assert.notNull(action, “Callback object must not be null”);

Connection con = DataSourceUtils.getConnection(obtainDataSource());

Statement stmt = null;

try {

stmt = con.createStatement();

applyStatementSettings(stmt);

T result = action.doInStatement(stmt);

handleWarnings(stmt);

return result;

}

catch (SQLException ex) {

// Release Connection early, to avoid potential connection pool deadlock

// in the case when the exception translator hasn’t been initialized yet.

String sql = getSql(action);

JdbcUtils.closeStatement(stmt);

stmt = null;

DataSourceUtils.releaseConnection(con, getDataSource());

con = null;

throw translateException(“StatementCallback”, sql, ex);

}

finally {

JdbcUtils.closeStatement(stmt);

DataSourceUtils.releaseConnection(con, getDataSource());

}

}

}

public interface Statement extends Wrapper, AutoCloseable {

ResultSet executeQuery(String sql) throws SQLException;

}

public abstract class JdbcAccessor implements InitializingBean {

@Nullable

private DataSource dataSource;

public void setDataSource(@Nullable DataSource dataSource) {

this.dataSource = dataSource;

}

}

三、更优雅的方式 -> 通过配置类方式实现


1、application.yml

server:

port: 8080

spring:

application:

name: test

datasource:

sqlserver:

jdbc-url: jdbc:sqlserver://127.0.0.1:1433;DatabaseName=test

driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver

username: sa

password: sa

postgres:

jdbc-url: jdbc:postgresql://127.0.0.1:5432/test

driverClassName: org.postgresql.Driver

username: postgres

password: 123456

2、配置类

package com.guor.config;

import org.apache.ibatis.session.SqlSessionFactory;

import org.mybatis.spring.SqlSessionFactoryBean;

import org.mybatis.spring.SqlSessionTemplate;

import org.mybatis.spring.annotation.MapperScan;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.boot.jdbc.DataSourceBuilder;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration

@MapperScan(basePackages = “com.guor.dao.postgres”, sqlSessionTemplateRef = “postgresSqlSessionTemplate”)

public class PostgresConfig {

@Bean(name = “postgresDataSource”)

@ConfigurationProperties(prefix = “spring.datasource.postgres”)

public DataSource postgresDataSource() {

return DataSourceBuilder.create().build();

}

@Bean(name = “postgresSqlSessionFactory”)

public SqlSessionFactory postgresSqlSessionFactory(@Qualifier(“postgresDataSource”) DataSource dataSource) throws Exception {

SqlSessionFactoryBean bean = new SqlSessionFactoryBean();

bean.setDataSource(dataSource);

bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(“com/guor/dao/postgres/mapping/*.xml”));

return bean.getObject();

}

@Bean(name = “postgresTransactionManager”)

public DataSourceTransactionManager postgresTransactionManager(@Qualifier(“postgresDataSource”) DataSource dataSource) {

return new DataSourceTransactionManager(dataSource);

}

@Bean(name = “postgresSqlSessionTemplate”)

public SqlSessionTemplate postgresSqlSessionTemplate(@Qualifier(“postgresSqlSessionFactory”) SqlSessionFactory sqlSessionFactory) throws Exception {

return new SqlSessionTemplate(sqlSessionFactory);

}

}

package com.guor.config;

import org.apache.ibatis.session.SqlSessionFactory;

import org.mybatis.spring.SqlSessionFactoryBean;

import org.mybatis.spring.SqlSessionTemplate;

import org.mybatis.spring.annotation.MapperScan;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.boot.jdbc.DataSourceBuilder;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.Primary;

import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration

@MapperScan(basePackages = “com.guor.dao.sqlserver”, sqlSessionTemplateRef = “sqlserverSqlSessionTemplate”)

public class SqlserverConfig {

@Bean(name = “sqlserverDataSource”)

@ConfigurationProperties(prefix = “spring.datasource.sqlserver”)

@Primary

public DataSource sqlserverDataSource() {

return DataSourceBuilder.create().build();

}

@Bean(name = “sqlserverSqlSessionFactory”)

@Primary

public SqlSessionFactory sqlserverSqlSessionFactory(@Qualifier(“sqlserverDataSource”) DataSource dataSource) throws Exception {

SqlSessionFactoryBean bean = new SqlSessionFactoryBean();

bean.setDataSource(dataSource);

bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(“com/guor/dao/sqlserver/mapping/*.xml”));

return bean.getObject();

}

@Bean(name = “sqlserverTransactionManager”)

@Primary

public DataSourceTransactionManager sqlserverTransactionManager(@Qualifier(“sqlserverDataSource”) DataSource dataSource) {

return new DataSourceTransactionManager(dataSource);

}

@Bean(name = “sqlserverSqlSessionTemplate”)

@Primary

public SqlSessionTemplate sqlserverSqlSessionTemplate(@Qualifier(“sqlserverSqlSessionFactory”) SqlSessionFactory sqlSessionFactory) throws Exception {

return new SqlSessionTemplate(sqlSessionFactory);

}

}

3、UserPostgresMapper

package com.guor.dao.postgres;

import java.util.List;

import java.util.Map;

public interface UserPostgresMapper {

List<Map<String, Object>> getUsersByPostgres();

}

4、UserPostgresMapper.xml

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注Java获取)

img

总结

蚂蚁面试比较重视基础,所以Java那些基本功一定要扎实。蚂蚁的工作环境还是挺赞的,因为我面的是稳定性保障部门,还有许多单独的小组,什么三年1班,很有青春的感觉。面试官基本水平都比较高,基本都P7以上,除了基础还问了不少架构设计方面的问题,收获还是挺大的。


经历这次面试我还通过一些渠道发现了需要大厂真实面试主要有:蚂蚁金服、拼多多、阿里云、百度、唯品会、携程、丰巢科技、乐信、软通动力、OPPO、银盛支付、中国平安等初,中级,高级Java面试题集合,附带超详细答案,希望能帮助到大家。

蚂蚁金服5面,总结了49个面试题,遇到的面试官都是P7级别以上

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!
验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!**

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注Java获取)

img

总结

蚂蚁面试比较重视基础,所以Java那些基本功一定要扎实。蚂蚁的工作环境还是挺赞的,因为我面的是稳定性保障部门,还有许多单独的小组,什么三年1班,很有青春的感觉。面试官基本水平都比较高,基本都P7以上,除了基础还问了不少架构设计方面的问题,收获还是挺大的。


经历这次面试我还通过一些渠道发现了需要大厂真实面试主要有:蚂蚁金服、拼多多、阿里云、百度、唯品会、携程、丰巢科技、乐信、软通动力、OPPO、银盛支付、中国平安等初,中级,高级Java面试题集合,附带超详细答案,希望能帮助到大家。

[外链图片转存中…(img-kpWoBsnJ-1712707842279)]

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值