current position:Home>[spring boot 27] springboot is configured with two databases, from Java to proficient PDF Baidu online disk
[spring boot 27] springboot is configured with two databases, from Java to proficient PDF Baidu online disk
2022-01-26 21:34:06 【m0_ fifty-four million eight hundred and sixty-one thousand fou】
/**
-
Close the connection
-
@param stmt sql Perform object
-
@param conn Database connection object
*/
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);
}
}
}
/**
-
Close the overloaded method of the resource
-
@param rs The object that handles the result set
-
@param stmt perform sql Object of statement
-
@param conn Objects connected to the database
*/
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);
}
}
}
}
Two 、jdbcTemplate.queryForList Source code exploration
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;
}
}
3、 ... and 、 More elegant way -> By configuring classes
1、application.yml
server:
port: 8080
spring:
application:
name: test
datasource:
sqlserve
《 A big factory Java Analysis of interview questions + Back end development learning notes + The latest architecture explanation video + Practical project source code handout 》
【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 Full content open source sharing
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、 Configuration class
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、 Browser access
[{“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”}]
[{“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
copyright notice
author[m0_ fifty-four million eight hundred and sixty-one thousand fou],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262134046331.html
The sidebar is recommended
- Spring IOC container loading process
- [thinking] the difference between singleton mode and static method - object-oriented programming
- Hadoop environment setup (MySQL environment configuration)
- 10 minutes, using node JS creates a real-time early warning system for bad weather!
- Git tool
- Force deduction algorithm - 92 Reverse linked list II
- What is the sub problem of dynamic programming?
- C / C + +: static keyword summary
- Idea does not have the artifacts option when configuring Tomcat
- Anaconda can't open it
guess what you like
-
I don't know how to start this
-
Matlab simulation of transportation optimization algorithm based on PSO
-
MySQL slow log optimization
-
[Vue] as the window is stretched (larger, smaller, wider and higher), the text will not be displayed
-
Popular Linux distributions for embedded computing
-
Suzhou computer research
-
After installing SSL Certificate in Windows + tomcat, the domain name request is not successful. Please answer!!
-
Implementation time output and greetings of jQuery instance
-
The 72 year old uncle became popular. Wu Jing and Guo fan made his story into a film, which made countless dreamers blush
-
How to save computer research
Random recommended
- Springboot implements excel import and export, which is easy to use, and poi can be thrown away
- The final examination subjects of a class are mathematical programming, and the scores are sorted and output from high to low
- Two pronged approach, Tsinghua Professor Pro code JDK and hotspot source code notes, one-time learning to understand
- C + + recursive knapsack problem
- The use of GIT and GitHub and the latest git tutorial are easy to understand -- Video notes of crazy God speaking
- PostgreSQL statement query
- Ignition database test
- Context didn't understand why he got a high salary?, Nginxfair principle
- Bootstrap switch switch control user's guide, springcloud actual combat video
- A list that contains only strings. What other search methods can be used except sequential search
- [matlab path planning] multi ant colony algorithm grid map path planning [including GUI source code 650]
- [matlab path planning] improved genetic algorithm grid map path planning [including source code phase 525]
- Iinternet network path management system
- Appium settings app is not running after 5000ms
- Reactnative foundation - 07 (background image, status bar, statusbar)
- Reactnative foundation - 04 (custom rpx)
- If you want an embedded database (H2, hsql or Derby), please put it on the classpath
- When using stm32g070 Hal library, if you want to write to flash, you must perform an erase. If you don't let it, you can't write continuously.
- Linux checks where the software is installed and what files are installed
- SQL statement fuzzy query and time interval filtering
- 69. Sqrt (x) (c + + problem solving version with vs runnable source program)
- Fresh students are about to graduate. Do you choose Java development or big data?
- Java project: OA management system (java + SSM + bootstrap + MySQL + JSP)
- Titanic passenger survival prediction
- Vectorization of deep learning formula
- Configuration and use of private image warehouse of microservice architect docker
- Relearn JavaScript events
- For someone, delete return 1 and return 0
- How does Java dynamically obtain what type of data is passed? It is used to judge whether the data is the same, dynamic data type
- How does the database cow optimize SQL?
- [data structure] chain structure of binary tree (pre order traversal) (middle order traversal) (post order traversal) (sequence traversal)
- Webpack packaging optimization solution
- 5. Operation element
- Detailed explanation of red and black trees
- redhat7. 9 install database 19C
- Blue Bridge Cup notes: (the given elements are not repeated) complete arrangement (arrangement cannot be repeated, arrangement can be repeated)
- Detailed explanation of springboot default package scanning mechanism and @ componentscan specified scanning path
- How to solve the run-time exception of test times
- Detailed explanation of k8s management tool kubectl
- Android system view memory command