MySQL database (refer to Ali Baba Java Development Manual)

  • To build the table Statute
    • name
      • Enforcement
        • Expression is the concept of whether or not the field name must is_xxx manner, the data type is unsigned tinyint (1 is represented, 0 for No).
          • Note: If any of the fields non-negative, must be unsigned .
          • Note: POJO class in any Boolean variables, do not add the prefix is , therefore, necessary to <resultMap> set mapping from is_xxx to Xxx's. Database representation is whether or not the value, use tinyint type, adhere to is_xxx naming to clarify its meaning and value ranges.
          • Positive Example: Expression field name is_deleted tombstone, 1 to delete, 0 indicates not deleted.
        • Table names, field names must be lowercase letters or numbers, start with a number banned, prohibited only the middle two numbers appear underlined. Modify the cost of a large database field names, because they can not carry out a pre-release, so the field names need to be carefully considered.
          • Experience: only use lowercase letters, position limit numbers, underscores, numbers more.
          • Description: MySQL is not case sensitive in Windows, but by default in Linux is case sensitive. Therefore, the database names, table names, field names, do not allow any uppercase letter, to avoid any further complications.
          • 正例:aliyun_admin,rdc_config,level3_name
          • 反例:AliyunAdmin,rdcConfig,level_3_name
        • Table name does not use a plural noun.
          • Description: Table name should represent only entity table of contents inside, should not represent the number of entities, DO corresponding to the class name is singular, idiomatic.
          • Experience: table usually pieces of data, of course, is plural, use a plural noun when it does not need a name.
        • Disabling reserved words, such as desc, range, match, delayed, please refer to the official MySQL reserved words.
          • Experience: postgresql different, such as user name can not be used as a table
        • Primary key index named pk_ field names; unique index called uk_ field names; ordinary index name was idx_ field name.
          • pk_ i.e., primary key; uk_ i.e. unique key; idx_ i.e. short index.
      • recommend
        • The best is to follow the table named "The role of business name _ the table."
          • 正例:alipay_task / force_project / trade_config
        • Library name and application name as consistent as possible.
    • Select the field type
      • Enforcement
        • Decimal type is decimal, prohibit the use of float and double.
          • Description: When stored, float and double precision loss problems there, probably when comparing values, get incorrect results. If the stored data exceeds the range decimal range, it is recommended to split into integer and fractional data and stored separately.
        • If the length of a string is almost equal, the use of fixed-length string type char.
        • varchar variable length strings, not pre-allocated storage space, a length not more than 5000, if the memory length is greater than this value, defined as the field type text, an independent list, with the corresponding primary key, to avoid affecting the efficiency index of other fields.
      • reference
        • Suitable character storage length, not only save space database tables, saving index storage, more importantly, to enhance the retrieval speed.
          • Positive Example: in the following table, in which the unsigned value to avoid misdirected negative, and indicates a range expanded.
            Object | Age interval | Type | byte | represents the range of
            | - | - | - | - | - |
            human | 150 years old | tinyint unsigned | 1 | unsigned value: 0 to 255
            turtle | Number hundredth | smallint unsigned | 2 | unsigned value: 0-65535
            dinosaur fossils | thousands of years | int unsigned | 4 | unsigned value: 0 to about 4.29 billion
            sun | about 50 million years | bigint unsigned | 8 | None symbol value: 0 th to 19 about 10
    • other
      • Enforcement
        • Table must have three fields: id, create_time, update_time.
          • Description: id shall wherein the primary key, type bigint unsigned, self-energizing single table, in steps of 1. create_time, type update_time are datetime types.
      • recommend
        • If you modify the field meaning or status field indicates the additional need to update the comment field.
        • Field allows appropriate redundancy to improve query performance, but must be considered consistent data. Redundant field should be followed:
          • 1) is not a frequent field changes.
          • 2) not long varchar fields, but it can not be a text field.
          • 3) is not the only index fields.
          • Positive Example: Product Category name using a high frequency, short field length, a substantially constant name, category name can be stored in the redundancy table associated, avoiding relational query .
        • Single table rows over 5 million lines or single-table capacity of more than 2GB, it is recommended sub-library sub-table.
          • Note: If the amount of data expected after three years failed to reach this level, you do not sub-library sub-table when creating tables.
  • Index Statute
    • Enforcement
      • Field has a unique operational characteristic, even when a combination of a plurality of fields, a unique index must be completed.
        • Note: Do not think that unique index affects the insert speed, the speed loss is negligible, but to improve the search speed is obvious; In addition, even at the application layer to do a very comprehensive check control, as long as there is no unique index, according to Murphy's Law, there must be dirty data generated.
      • More than three tables prohibit join. Need to join the field, data types must be absolutely consistent; multi-table associated with the query, ensure that fields are associated with the need to have an index.
        • Note: Also note that even if the two-table join table index, SQL performance.
      • When creating an index on a varchar field, you must specify the length of the index, no need for indexing the whole field, you can determine the length of an index based on the actual text of discrimination.
        • Description: the length of the discrimination index is a contradiction, the general type of string data length of the index 20, the discrimination will be more than 90%, can count (distinct left (column name, index length)) / count (*) to determine the degree of differentiation.
      • Search page is strictly prohibited left vague or fuzzy whole, if necessary, please take the search engine to solve.
        • Explanation: The index file with the most left-prefix match the characteristics of the B-Tree, and if the value is left undetermined, it can not use this index.
    • recommend
      • If there is order by the scene, note the use of the orderliness of the index. The final order by the field is part of the composite index, and the index on a combination of final order, to avoid the appearance file_sort affect query performance.
        • Positive Example: where a = and b = order by c; index:?? A_b_c
        • Anti Example: If there is an index range query, then the index can not be orderly use, such as: WHERE a> 10 ORDER BY b; a_b not sorted index.
      • Use an index to cover the query, to avoid back to the table.
        • Note: If you need a book to know what Chapter 11 is titled, will open that page in Chapter 11 corresponding to it? Directory look like, this directory is to play the role of covering indexes.
        • Positive examples: the ability to establish a kind of sub-index primary key index, the only index, the general index of three, and a covering index is only one kind of an effect the query, the results explain the use, extra columns will appear: using index.
      • Or delay associated with the use of sub-query optimization super multi-page scene.
        • Description: MySQL is not the skip offset lines, but taking offset + N line, and then return to give up before the offset rows, return N rows , that when offset is particularly large, the efficiency is very low, or control the total number of pages returned or on the number of pages exceeds a certain threshold will be rewritten SQL.
        • Positive examples: the first segment id need to get to quickly locate, and then associate:
          • SELECT a.* FROM 表1 a, (select id from 表1 where 条件 LIMIT 100000,20 ) b where a.id=b.id
      • SQL performance optimization goal: to reach at least the level range, the requirement is ref level, if you can be consts best.
        • Description:
        • 1) consts single table can only have a matching row (primary key or unique index), data can be read in the optimization stage.
        • 2) ref refers to the use of an ordinary index (normal index).
        • 3) range of the index range search.
        • Counter-example: explain the results table, type = index, the index of physical files full scan, speed is very slow, the index level is also relatively low range, and a full table scan is trivial.
      • Build composite index of time, the highest in the left most discrimination.
        • Positive example: if where a = and b =,? ? If almost close to unique values of a column, then you only need a single idx_a index can be built . Description: When a non-equal sign equal sign and mixed, at the time of construction of the index, the column pre-condition of the equal sign. Such as: where c> and d = c then even higher degree of differentiation, d must be at the forefront of the index, that index idx_d_c??.
      • Prevent implicit conversion caused because of the different field types, resulting in failure of the index.
    • reference
      • When you create an index to avoid extreme misunderstanding follows:
        • 1) Do not abuse rather short. I think a query needs to build an index.
        • 2) before quantity. I think the index will consume space, a serious slow down the speed of the new record and update the line.
        • 3) boycott unique index. The only think that all of the business need to be addressed in the application layer through the "check the plug after the first" approach.
  • SQL statements
    • Enforcement
      • Do not use the count (column name) or count (constant) instead of count ( ), count ( ) syntax is defined by the number of SQL92 standard statistical line, nothing to do with the database, nothing to do with NULL and non-NULL.
        • Description: ** count (*) counts the value NULL row, while count (column name) does not count rows in this column is NULL values. **
      • count (distinct col) calculate the number of rows do not overlap other than the NULL column, note count (distinct col1, col2) If a NULL is full, even if the other columns have different values, but also returns to zero.
      • NPE should pay attention to a problem when the value of the whole column is NULL, count (col) returns a value of 0, but the sum (col) returns a value of NULL, and therefore the use of sum ().
        • Positive Example: Use a manner to avoid problems NPE sum of: the SELECT the IFNULL (the SUM (column), 0) the FROM Table;
      • Using the ISNULL () to determine whether a NULL value.
        • Description: NULL direct comparison with any value will be NULL.
        • 1) NULL <> NULL result returned is NULL, and not false.
        • 2) NULL = NULL result returned is NULL, and not true.
        • 3) NULL <> 1 result returned is NULL, and not true.
      • When writing code paging query logic, if the count is zero should be returned directly to avoid the implementation of pagination statement back.
      • Not use foreign key with a cascade, all foreign key concepts that must be addressed in the application layer.
        • Description: The relationship between student achievement and example, students student_id table is the primary key, then the results table student_id was foreign keys. If you update the student table student_id, while triggering the results table student_id update, that is, cascading updates. Foreign keys with cascading updates for stand-alone low concurrency, not suitable for distributed, highly concurrent cluster; cascade update is strong blocker, there is a risk database update storm; insert foreign keys affect the speed of the database.
      • Prohibit the use of stored procedures, stored procedures, difficult to debug and extend, and no portability.
      • When the data revision (in particular, delete, modify recording operation), first select, to avoid accidentally deleted, confirmation in order to perform the update statement.
    • recommend
      • in operation can be avoided, avoid, if it can not avoid the need to carefully assess the number of elements in the set back control in the 1000's.
    • reference
      • If there is an international need, all the characters are stored and represent, are utf-8 encoding, note the difference between the character of statistical functions.
        • Description:
          • The SELECT LENGTH ( "light work"); return 12
          • The SELECT CHARACTER_LENGTH ( "light work"); return to 4
          • If you need to store look, then the choice utf8mb4 for storage, pay attention to it and utf-8 encoded difference.
      • TRUNCATE TABLE is faster than DELETE speed, and fewer system and transaction log resources used, but TRUNCATE no transaction does not trigger trigger, may cause an accident, it is not recommended to use this statement in the development of the code.
        • Description: TRUNCATE TABLE and DELETE statement with no WHERE clause is identical in functionality.
  • ORM mapping
    • Enforcement
      • In the table query, do not always use * as a list of fields of inquiry, which fields need to be clearly stated.
        • Description:
        • 1) increase Query Analyzer analytical costs.
        • 2) changes in the field and easily resultMap inconsistent.
        • 3) increasing the field network useless consumption, especially in the field of type text.
        • Experience: In addition count (*) outside?
      • POJO class Boolean attribute can not be added is, but must be added to the database field is_, it requires a mapping between fields in the attribute resultMap.
        • Note: See the definition of a database field definition POJO class and predetermined increase in the mapping <resultMap> in is required. In MyBatis Generator generated code, corresponding to the required modification.
      • Do not use resultClass as return parameter, even if all the class name and attribute database fields correspond, also need to be defined; in turn, are bound to each table has a corresponding POJO class.
        • Explanation: The configuration mapping between the field and DO classes decoupled and easy maintenance.
      • sql.xml configuration parameters: # {}, # param # Do not use $ {} in this way is prone to SQL injection.
      • iBATIS comes queryForList (String statementName, int start, int size) is not recommended.
        • Description: This is achieved statementName is to take all the records corresponding to the SQL statement in the database, then start by taking subList, size of the subset.
        • 正例:Map<String, Object> map = new HashMap<>();map.put("start", start);map.put("size", size);
      • Do not allow direct output to take HashMap and Hashtable as a query result set.
        • Description: resultClass = "Hashtable", will be put into the field name and value, but the value is not controllable type .
      • When updating the data table records, update records must gmt_modified field value corresponding to the current time.
    • recommend
      • Do not write a large and comprehensive data update interface. Incoming for the POJO class, whether or not their target update fields, have carried update table set c1 = value1, c2 = value2, c3 = value3; it is not right. The implementation of SQL, do not update the field without changes, one error-prone; the second is the low efficiency; third is to increase binlog storage.
    • reference
      • Do not abuse @Transactional affairs. Transactions affect QPS database, in addition to using the transaction rollback place to consider all aspects of the program, including the rollback cache, search engine rollback, the message compensation, and other statistical correction.
        • Experience: Must inside operations support rollback.
      • <IsEqual> compareValue is constant in comparison with the attribute value, typically a number, indicates this condition to bring equal; <isNotEmpty> expressed not empty is not performed is null; <isNotNull> means that no value is null .

Guess you like

Origin www.cnblogs.com/wyp1988/p/11958290.html