Manage database structure information in Multi-sample mode

Source: Internet
Author: User

The multi-instance mode is a mode in which a class can have multiple instances. It is a natural promotion of the single-instance mode. It has the following features: 1. This class can have multiple instances; 2. The class itself creates and manages its instances; 3. The class itself provides its instances to the outside world. JadePool uses the limited multi-sample mode to manage database structure information. In JadePool open-source tools, DbCenter is responsible for managing the database structure information of transactional databases, and DbAccess is responsible for managing the database structure information of non-transactional databases, they comply with Db planning methods. They manage their own Table and Field objects. This article takes DbCenter as an example to briefly introduce the implementation process of database structure information management. Why choose the limited multi-instance mode to manage database structure information? This may be the most reasonable choice. database structure information, as shared resources in the entire software system, may need to be used in large quantities. Therefore, such resources should reside in the memory. DbCenter currently provides four instances. Each instance is responsible for managing the structure information of a database. In theory, the software system can manage up to four databases at the same time. Generally, you only need one instance, to implement interaction between two different databases, You Can instantiate two instances. The limited multi-instance mode ensures that users operate on several different databases simultaneously. What does DbCenter do? 1. Create a corresponding DbCenter instance based on the user request such as the ProcessVO constructor, initialize the instance, and submit the instance to the user. 2. instantiate the class attributes, including: Database drive name, database framework name, database name, database table name set. 3. Create a Table object for each Table in the database; 4. Create a Field object for each Table Field. The above four steps are used to completely extract the structure information of the entire database and supply it to the program for next call. The following is part of the source code, the source code in detail, you can download the JadePool-1.0-GBK resource file to get. [Java] synchronized private void init (Connection _ con) {this. con = _ con; try {// schema = con. getSchema (); catalog = con. getCatalog (); // database name dm = con. getMetaData (); driverName = dm. getDriverName (); Set <String> tableNameSet = new java. util. linkedHashSet (); // TABLE name set String [] types = {"TABLE"}; ResultSet rs = dm. getTables (null, types); // obtain the names of all tables in the database while (rs. next () {String tableName = rs. ge TString ("TABLE_NAME"); tableNameSet. add (tableName);} Object [] o = tableNameSet. toArray (); tableNames_tmp = new String [o. length]; tableNames = new String [o. length]; for (int I = 0; I <o. length; I ++) {tableNames_tmp [I] = (String) o [I]. toString (); tableNames [I] = (String) o [I]. toString (). toLowerCase ();} if (tableNames_tmp! = Null) {for (int I = 0; I <tableNames_tmp.length; I ++) {initTableMap (tableNames_tmp [I]); // capital} instance_times ++ ;} catch (SQLException ex) {Logger. getLogger (DbCenter. class. getName ()). log (Level. SEVERE, ex. getMessage (), ex);} finally {// con. close (); Share con, cannot close, by calling Db instance. getCon () user close} [java]/*** should be here, and the Field and the key value information of each table should also be initialized. Note: Use ResultSet rs = dm. getColumns (catalog, * null, tableName, nul L);/when using the derby database, it is case sensitive. Therefore, the ** @ param tableName value can only be obtained through the dm prototype, which causes case sensitivity problems, during the operation, the case cannot be converted. It can only be converted to lowercase at the end. */synchronized private void initTableMap (String tableName) throws SQLException {Table table = getTable (tableName. toLowerCase (); if (table = null) {table = new Table ();} table. setName (tableName. toLowerCase (); Set fieldSet = new java. util. linkedHashSet (); Set keySet = new java. util. linkedHa ShSet (); if (con! = Null) {ResultSet rs = dm. getColumns (catalog, null, tableName, null); // obtain all fields in the table // see ResultSet rs = dm. getProcedureColumns (catalog, catalog, driverName, tableName );//? Map <String, Field> field_map = new LinkedHashMap (); while (rs. next () {String name = rs. getString ("COLUMN_NAME"); // For the parameter values, see dm. the help documentation fieldSet for getColumns (catalog, null, tableName, null. add (lowerCase (name); Field f = new Field (); f. setName (lowerCase (name); // DATA_TYPE int => SQL type from java. SQL. types/* Each column description has the following columns: TABLE_CAT String => table catalog (may be n Ull) TABLE_SCHEM String => table schema (may be null) TABLE_NAME String => table name COLUMN_NAME String => column name DATA_TYPE int => SQL type from java. SQL. types TYPE_NAME String => Data source dependent type name, for a UDT the type name is fully qualified COLUMN_SIZE int => column size. BUFFER_LENGTH is not used. DECIMAL_DIGITS int => the number of fractional digits. null is returned for dat A types where DECIMAL_DIGITS is not applicable. NUM_PREC_RADIX int => Radix (typically either 10 or 2) NULLABLE int => is NULL allowed. columnNoNulls-might not allow NULL values columnNullable-definitely allows NULL values-nullability unknown REMARKS String => comment describing column (may be null) COLUMN_DEF String => default value for the column, which shoshould be inte Rpreted as a string when the value is enclosed in single quotes (may be null) SQL _DATA_TYPE int => unused SQL _DATETIME_SUB int => unused CHAR_OCTET_LENGTH int => for char types the maximum number of bytes in the column ORDINAL_POSITION int => index of column in table (starting at 1) IS_NULLABLE String => ISO rules are used to determine the nullability for a column. YES --- if the column can includ E NULLs NO --- if the column cannot include NULLs empty string --- if the nullability for the column is unknown SCOPE_CATALOG String => catalog of table that is the scope of a reference attribute (null if DATA_TYPE isn' t REF) SCOPE_SCHEMA String => schema of table that is the scope of a reference attribute (null if the DATA_TYPE isn't REF) SCOPE_TABLE String => table name that this the scope of Reference attribute (null if the DATA_TYPE isn't REF) SOURCE_DATA_TYPE short => source type of a distinct type or user-generated Ref type, SQL type from java. SQL. types (null if DATA_TYPE isn't DISTINCT or user-generated REF) IS_AUTOINCREMENT String => Indicates whether this column is auto incremented YES --- if the column is auto incremented NO --- if the column is not auto incremented empty strin G --- if it cannot be determined whether the column is auto incremented IS_GENERATEDCOLUMN String => Indicates whether this is a generated column YES --- if this a generated column NO --- if this not a generated column empty string --- if it cannot be determined whether this is a generated column */String dataType = rs. getString ("DATA_TYPE"); f. setSqlType (new Integer (dataType ). intValue (); // For example: jav A. SQL. types. INTEGER String type = rs. getString ("TYPE_NAME"); // For example, BIGINT f. setTypeName (lowerCase (type); String position = rs. getString ("ORDINAL_POSITION"); // The position f in the table. setPosition (position); String size = rs. getString ("COLUMN_SIZE"); // user-defined field length f. setSize (size); String bufferLength = rs. getString ("BUFFER_LENGTH"); // field buffer size f. setBufferLength (bufferLength); String decimal = rs. getString ("DECIMAL_DIGITS" ); // Precision f. setDecimal (decimal); String defaultValue = rs. getString ("COLUMN_DEF"); f. setDefaultValue (defaultValue); String remark = rs. getString ("REMARKS"); f. setRemark (remark); String nullable = rs. getString ("NULLABLE"); // value: 0 | 1, 1, 0, 0, if ("0 ". equals (nullable) {f. setNullable (false);} if ("1 ". equals (nullable) {f. setNullable (true);} field_map.put (name. toLowerCase (), f);} table. setFieldMap (Field_map); // Field name: ing table of the Field Object; // obtain the Field name array Object [] o = fieldSet. toArray (); String [] fields = new String [o. length]; for (int I = 0; I <o. length; I ++) {fields [I] = (String) o [I]). toLowerCase ();} table. setFields (fields); // The primary key, starting with ResultSet rsk = dm. getPrimaryKeys (catalog, null, tableName); // All are tested by the jdbc driver of the new SQL Server and MySQL, and all primary keys are returned // ResultSet rsk = dm. getPrimaryKeys (catalog, "%", tableName); // previous versions The MySQL jdbc driver of returns all primary keys // while (rsk. next () {String name = rsk. getString ("COLUMN_NAME"); // The primary key name keySet. add (lowerCase (name. toLowerCase (); //} Object [] k = keySet. toArray (); String [] keys = new String [k. length]; for (int I = 0; I <k. length; I ++) {keys [I] = (String) k [I]; field_map.get (keys [I]). setPrimarykey (true); // use mssql, mysql, derby} table. setKeys (keys); // The primary key, and the end. // you can specify the Field attribute typeclassnm. E value String squeryFieldTypeClassName = "select * from" + tableName. toLowerCase () + "where" + table. getFields () [0] + "is null"; if (table. getKeys (). length> 0) {squeryFieldTypeClassName = "select * from" + tableName. toLowerCase () + "where" + table. getKeys () [0] + "is null";} Statement stmt0 = con. createStatement (); ResultSet rscname = stmt0.executeQuery (squeryFieldTypeClassName); ResultSetM EtaData rsmd = rscname. getMetaData (); for (int I = 1; I <= rsmd. getColumnCount (); I ++) {String fieldNmae = rsmd. getColumnName (I); field_map.get (fieldNmae. toLowerCase ()). setTypeClassName (rsmd. getColumnClassName (I); // use mssql, mysql, derby} stmt0.close ();} tableMap. put (tableName. toLowerCase (), table); // initialize Table} in the implementation of JadePool Based on the HashMap relational data ing technology, the Db family dynamically extracts and manages database structure information through the limited multi-sample mode, it is the big manager of JadePool. This is the most fundamental difference between the HRM product and the orm product. It is an important prerequisite for JadePool to be efficient, concise, and intelligent. By the way, DbAccess is responsible for extracting the database structure information for managing non-transactional databases. The important difference between using DbCenter and DbAccess is whether the database supports transactions. In a transaction-type database, you can use ResultSet rsk = dm. getPrimaryKeys (catalog, null, tableName); the statement extracts the primary key information, which is not currently supported by the transaction database. Currently, JadePool treats the first field of a non-transactional database table as the primary key. How to instantiate DbCenter? ProcessVO is the core class of JadePool and is mainly used to implement database CRUD or DML operations. At present, this class has three constructor 1, ProcessVO (); it will instantiate the defaultDb instance 2 and ProcessVO (Connection con) in DbCenter ); it will instantiate userDb instance 3 and ProcessVO (Connection con, int connectionType) in DbCenter. It will be based on the connectionType value, for example, according to cn. jadepool. SQL. dbConnectionType. USING_DB_01 instantiate db_01 according to cn. jadepool. SQL. dbConnectionType. USING_DB_02 instantiate db_02. Example: ProcessVO pvo = new ProcessVO (); Db db = pvo. getDb ();...... in this case, you can access the database structure information, table structure information, and field structure information through the database. If you are interested in JadePool, you can download the jadepool-1.0-GBK from the following URL

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.