Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to adapt and manage dynamic data sources based on JDBC schema

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "how to adapt and manage dynamic data sources based on JDBC mode". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Relational data sources 1. Dynamic data sources

Dynamic management of the basic functions of data sources: data source loading, container maintenance, persistence management.

2. Relational database

The relational databases of different manufacturers provide different link methods, driver packages and driver class names. Java database connection API,JDBC is an application program interface used to regulate how client programs access the database in Java language. it provides methods such as querying and updating data in the database, and adapts to most relational databases.

3. Adaptation elements

Core elements: driver package, driver class name, URL format, default port.

There are many relational databases, which must be incomplete and can be perfected according to the needs.

Public enum DataSourceType {MySql ("MySql", "com.mysql.jdbc.Driver"), Oracle ("Oracle", "oracle.jdbc.OracleDriver"), DB2 ("DB2", "com.ibm.db2.jcc.DB2Driver"); private String dataSourceName; private String driverClassName; public static String getDriver (String dataSourceName) {DataSourceType [] types = DataSourceType.values () For (DataSourceType type: types) {if (type.getDataSourceName (). Equals (dataSourceName)) {return type.getDriverClassName ();}} return null;} DataSourceType (String dataSourceName,String driverClassName) {this.dataSourceName = dataSourceName; this.driverClassName = driverClassName;}} 4, JDBC basic API

DriverManager

Manage the basic service API of the JDBC driver. Call the method Class.forName to explicitly load the driver class, which is just suitable for the business scenario of the dynamic data source, where the data source type is unknown. Once the Driver class is loaded and registered with the DriverManager class, it can be used to establish a connection with the database.

DataSource

The DataSource interface, implemented by the driver provider, is responsible for establishing a connection to the database and is often used to obtain Connection objects for operational data when accessing the database in an application.

Connection

The Connection interface represents the connection to a specific database. To operate the database data, the first step is to obtain the database connection. The Connection implementation is like opening a channel between the application and the database, and the Connection instance can be obtained through either the DriverManager class or the DataSource class.

II. Link and management

Here are several core class encapsulation ideas: modular function, API separately encapsulated, if you need to adapt to deal with all kinds of data source types, respectively can be abstracted upward, down to customize the adaptation strategy, the basic consciousness under the influence of design patterns.

1. Link tool

Based on DriverManager management data source driver loading, link acquisition and so on.

Public class ConnectionUtil {public static synchronized Connection getConnect (String driverClassName,String userName, String passWord,String jdbcUrl) {Properties prop = new Properties (); prop.put ("user", userName); prop.put ("password", passWord); return connect (driverClassName,prop,jdbcUrl) } private static synchronized Connection connect (String driverClassName, Properties prop,String jdbcUrl) {try {Class.forName (driverClassName); DriverManager.setLoginTimeout (JdbcConstant.LOGIN_TIMEOUT); return DriverManager.getConnection (jdbcUrl, prop);} catch (Exception e) {e.printStackTrace () } return null;}} 2, API utility class

Provide API configuration acquisition class, load the required data source API, close resources and other basic operations.

@ Componentpublic class JdbcConfig {/ * get data source connection * / public Connection getConnection (ConnectionEntity connectionEntity) {String dataTypeName = connectionEntity.getDataTypeName (); String driverClassName = DataSourceType.getDriver (dataTypeName); if (driverClassName = = null) {throw new RuntimeException ("this data source type is not supported");} connectionEntity.setDriverClassName (driverClassName) Return ConnectionUtil.getConnect (connectionEntity.getDriverClassName (), connectionEntity.getUserName (), connectionEntity.getPassWord (), connectionEntity.getJdbcUrl ());}} 3, data source container

Maintain a Map container to manage basic requirements such as adding, deleting, and dynamic fetching of data sources.

@ Componentpublic class DataSourceFactory {private volatile Map dataSourceMap = new HashMap (); @ Resource private JdbcConfig jdbcConfig; @ Resource private ConnectionMapper connectionMapper; / * * data source API wrapper * / private static DataSource getDataSource (ConnectionEntity connectionEntity) {DruidDataSource datasource = new DruidDataSource (); datasource.setUrl (connectionEntity.getJdbcUrl ()); datasource.setUsername (connectionEntity.getUserName ()); datasource.setPassword (connectionEntity.getPassWord ()) Datasource.setDriverClassName (connectionEntity.getDriverClassName ()); return datasource;} / * * get JDBC link * / public JdbcTemplate getById (Integer id) {return new JdbcTemplate (dataSourceMap.get (id));} / * remove data source * / public void removeById (Integer id) {dataSourceMap.remove (id) } / * add data source management * Note the method here. After connection verification, call * / public void addDataSource (ConnectionEntity connectionEntity) {DataSource dataSource = getDataSource (connectionEntity); dataSourceMap.put (connectionEntity.getId (), dataSource);}} 4. Process test

Based on the dynamic data source, query the table data, the operation here represents the known table structure, in fact, the table structure of the dynamic data source needs to dynamically obtain the table field again in order to operate. (dynamic reading and writing of data in the next section will be described in more detail)

@ Api (value = "JdbcQueryController") @ RestControllerpublic class JdbcQueryController {@ Resource private DataSourceFactory dataSourceFactory; @ GetMapping ("getList") public List getList (@ RequestParam ("id") Integer id) {String sql = "SELECT * FROM jm_connection WHERE state='1'"; JdbcTemplate jdbcTemplate = dataSourceFactory.getById (id); List connectionEntities = jdbcTemplate.query (sql, new BeanPropertyRowMapper (ConnectionEntity.class); return connectionEntities;}} III. Batch management

To persist the configuration information of the data source, one more step is used to store the configuration information, and the input information is loaded into the container and dynamically obtained when it is used.

1. Mapper structure of database table

A table structure that stores configuration information and converts Mapper files.

SELECT * FROM jm_connection WHERE state='1' 2, persistence management

Test whether the data source link is successful, the available data source link, and the configuration information is stored in the database.

@ Servicepublic class ConnectionServiceImpl implements ConnectionService {@ Resource private ConnectionMapper connectionMapper; @ Resource private JdbcConfig jdbcConfig; @ Resource private DataSourceFactory dataSourceFactory; @ Override public boolean testConnection (ConnectionEntity connectionEntity) {return jdbcConfig.getConnection (connectionEntity)! = null;} @ Override public boolean addConnection (ConnectionEntity connectionEntity) {Connection connection = jdbcConfig.getConnection (connectionEntity); if (connection! = null) {int addFlag = connectionMapper.insert (connectionEntity) If (addFlag > 0) {dataSourceFactory.addDataSource (connectionEntity); return true;}} return false;}} 3, dynamic loading

In the container factory class, add an initialization method to load the data source configuration information that is loaded into the library.

@ Componentpublic class DataSourceFactory {/ * initialize the JDBC link API * / @ PostConstruct public void init () {List connectionList = connectionMapper.getAllList (); if (connectionList! = null & & connectionList.size () > 0) {for (ConnectionEntity connectionEntity:connectionList) {Connection connection = jdbcConfig.getConnection (connectionEntity) If (connection! = null) {DataSource dataSource = getDataSource (connectionEntity); dataSourceMap.put (connectionEntity.getId (), dataSource);}} "how to adapt and manage dynamic data sources based on JDBC mode" ends here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report