Springboot配置两个数据库

本文介绍了如何在SpringBoot应用中使用MyBatis框架,通过配置类的方式管理不同的数据源(如SQLServer和PostgreSQL),以及如何创建和使用SqlSessionFactory和SqlSession,以实现数据库操作的优雅执行和资源管理。
摘要由CSDN通过智能技术生成

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

<?xml version="1.0" encoding="UTF-8" ?>

SELECT * FROM t_user

5、UserSqlserverMapper

package com.guor.dao.sqlserver;

import java.util.List;

import java.util.Map;

public interface UserSqlserverMapper {

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

}

6、UserSqlserverMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>

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<Map<String, Object>> getUsersBySqlserver(){

return userMapper.getUsersFromSqlserver();

}

@Autowired

private UserPostgresMapper userPostgresMapper;

@GetMapping(“/getUsersByPostgres”)

public List<Map<String, Object>> 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

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns=“http://maven.apache.org/POM/4.0.0”

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

org.springframework.boot

spring-boot-starter-web

org.mybatis.spring.boot

mybatis-spring-boot-starter

2.0.1

org.postgresql

postgresql

commons-io

commons-io

2.5

com.microsoft.sqlserver

mssql-jdbc

com.google.guava

guava

20.0

cglib

cglib-nodep

3.2.4

org.springframework.boot

spring-boot-configuration-processor

true

com.alibaba

druid

1.0.16

test

四、配置类内容初探


1、SqlSessionFactory

SqlSessionFactory是MyBatis的关键对象,它是个单个数据库映射关系经过编译后的内存镜像,SqlSessionFactory对象的实例可以通过SqlSessionFactoryBuilder对象类获得,而SqlSessionFactoryBuilder则可以从XML配置文件或一个预先定制的Configuration的实例构建出SqlSessionFactory的实例。每一个MyBatis的应用程序都以一个SqlSessionFactory对象的实例为核心,同时SqlSessionFactory也是线程安全的,SqlSessionFactory一旦被创建,应该在应用执行期间都存在,在应用运行期间不要重复创建多次,建议使用单例模式,SqlSessionFactory是创建SqlSession的工厂。

2、SqlSession

SqlSession是MyBatis的关键对象,是执行持久化操作的独享,类似于JDBC中的Connection。它是应用程序与持久层之间执行交互操作的一个单线程对象,也是MyBatis执行持久化操作的关键对象。SqlSession对象完全包含以数据库为背景的所有执行SQL操作的方法,它的底层封装了JDBC连接,可以用SqlSession实例来直接执行被映射的SQL语句。每个线程都应该有它自己的SqlSession实例。SqlSession的实例不能被共享,同时SqlSession也是线程不安全的,绝对不能讲SqlSeesion实例的引用放在一个类的静态字段甚至是实例字段中。也绝不能将SqlSession实例的引用放在任何类型的管理范围中,比如Servlet当中的HttpSession对象中,使用完SqlSeesion之后关闭Session很重要,应该确保使用finally块来关闭它。

3、SqlSession创建过程

mybatis框架主要是围绕着SqlSessionFactory进行的,创建过程大概如下:

  1. 定义一个Configuration对象,其中包含数据源、事务、mapper文件资源以及影响数据库行为属性设置settings。

  2. 通过配置对象,则可以创建一个SqlSessionFactoryBuilder对象
    自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

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

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

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

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

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

img

最后

做任何事情都要用心,要非常关注细节。看起来不起眼的、繁琐的工作做透了会有意想不到的价值。
当然要想成为一个技术大牛也需要一定的思想格局,思想决定未来你要往哪个方向去走, 建议多看一些人生规划方面的书籍,多学习名人的思想格局,未来你的路会走的更远。

更多的技术点思维导图我已经做了一个整理,涵盖了当下互联网最流行99%的技术点,在这里我将这份导图分享出来,以及为金九银十准备的一整套面试体系,上到集合,下到分布式微服务

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门即可获取!
这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!**

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

img

最后

做任何事情都要用心,要非常关注细节。看起来不起眼的、繁琐的工作做透了会有意想不到的价值。
当然要想成为一个技术大牛也需要一定的思想格局,思想决定未来你要往哪个方向去走, 建议多看一些人生规划方面的书籍,多学习名人的思想格局,未来你的路会走的更远。

更多的技术点思维导图我已经做了一个整理,涵盖了当下互联网最流行99%的技术点,在这里我将这份导图分享出来,以及为金九银十准备的一整套面试体系,上到集合,下到分布式微服务

[外链图片转存中…(img-PuvJS9Jb-1711826092870)]

[外链图片转存中…(img-a2ibqp9E-1711826092870)]

[外链图片转存中…(img-oroeGhvk-1711826092871)]

[外链图片转存中…(img-Sam2OUWJ-1711826092871)]

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门即可获取!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值