【Spring Boot 27,Java开发两年

    } 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 <T> List<T> query(String sql, RowMapper<T> rowMapper) throws DataAccessException {

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

}



@Override

@Nullable

public <T> T query(final String sql, final ResultSetExtractor<T> 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<T>, 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> T execute(StatementCallback<T> 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"));

完结

Redis基于内存,常用作于缓存的一种技术,并且Redis存储的方式是以key-value的形式。Redis是如今互联网技术架构中,使用最广泛的缓存,在工作中常常会使用到。Redis也是中高级后端工程师技术面试中,面试官最喜欢问的问题之一,因此作为Java开发者,Redis是我们必须要掌握的。

Redis 是 NoSQL 数据库领域的佼佼者,如果你需要了解 Redis 是如何实现高并发、海量数据存储的,那么这份腾讯专家手敲《Redis源码日志笔记》将会是你的最佳选择。

ataSource) throws Exception {

    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();

    bean.setDataSource(dataSource);

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

完结

Redis基于内存,常用作于缓存的一种技术,并且Redis存储的方式是以key-value的形式。Redis是如今互联网技术架构中,使用最广泛的缓存,在工作中常常会使用到。Redis也是中高级后端工程师技术面试中,面试官最喜欢问的问题之一,因此作为Java开发者,Redis是我们必须要掌握的。

Redis 是 NoSQL 数据库领域的佼佼者,如果你需要了解 Redis 是如何实现高并发、海量数据存储的,那么这份腾讯专家手敲《Redis源码日志笔记》将会是你的最佳选择。

[外链图片转存中…(img-KmFhwGZJ-1628388888574)]

感兴趣的朋友可以通过点赞+戳这里的方式免费获取腾讯专家手写Redis源码日志笔记pdf版本!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值