【Spring Boot 27】Springboot配置两个数据库,java从入门到精通pdf百度网盘

【Spring Boot 27】Springboot配置两个数据库,java从入门到精通pdf百度网盘,第1张

【Spring Boot 27】Springboot配置两个数据库,java从入门到精通pdf百度网盘

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);

}

}

}

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> 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 + “]”);

}

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:

sqlserve

《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享

r:

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> getUsersByPostgres();

}

4、UserPostgresMapper.xml

SELECt * FROM t_user

5、UserSqlserverMapper

package com.guor.dao.sqlserver;

import java.util.List;

import java.util.Map;

public interface UserSqlserverMapper {

List> getUsersFromSqlserver();

}

6、UserSqlserverMapper.xml

SELECt * FROM t_user

7、controller

package com.guor.controller;

import java.util.List;

import java.util.Map;

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

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.guor.dao.postgres.UserPostgresMapper;

import com.guor.dao.sqlserver.UserSqlserverMapper;

@RestController

@RequestMapping(“user”)

public class UserController {

@Autowired

private UserSqlserverMapper userMapper;

@GetMapping("/getUsersBySqlserver")

public List> getUsersBySqlserver(){

return userMapper.getUsersFromSqlserver();

}

@Autowired

private UserPostgresMapper userPostgresMapper;

@GetMapping("/getUsersByPostgres")

public List> getUsersByPostgres(){

return userPostgresMapper.getUsersByPostgres();

}

}

8、浏览器访问

http://localhost:8080/user/getUsersByPostgres

[{“id”:1,“name”:“zs”,“age”:18,“version”:“1”,“deleted”:0},{“id”:1,“name”:“ls”,“age”:28,“creator_id”:87368736,“created_time”:“2021-06-11T02:43:48.000+0000”},{“id”:2,“name”:“ww”,“age”:35,“creator_id”:87368736,“created_time”:“2021-06-11T05:29:20.000+0000”}]

http://localhost:8080/user/getUsersBySqlserver

[{“id”:1,“name”:“zs”,“age”:18},{“id”:2,“name”:“ls”,“age”:20}]

9、pom

xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation=“http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”>

4.0.0

com.guor

test-pom

1.0.0

…/pom.xml

test

test

test

1.0.0

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5672884.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存