Java Coding Specification 14 (MySQL-SQL statement and ORM mapping)

1. SQL statement


Other related articles
Java Coding Specification 1 (Programming Specification - Naming Style)
Java Coding Specification 2 (Programming Specification - Constant Definition)
Java Coding Specification 3 (Programming Specification - Code Format)
Java Coding Specification 4 (Programming Specification - OOP Specification)
Java Coding Specification 5 (Programming Specification - Collection Processing)
Java Coding Specification 6 (Programming Specification - Concurrent Processing)
Java Coding Specification 7 (Programming Specification - Control Statement)
Java Coding Specification 8 (Programming Specification - Annotation Specification and Others)
Java Coding Specification 9 (Exception Log )
Java Coding Specification 10 (Unit Test)
Java Coding Specification 11 (Security Specification)
Java Coding Specification 12 (MySQL-Table Building Specification)
Java Coding Specification 13 (MySQL-Index Specification)
Java Coding Specification 14 (MySQL-SQL Statement and ORM Mapping )
Java Coding Specification 15 (Project Structure)


  1. [Mandatory] Do not use count(列名)or count(常量)to replace count(*)it. It count(*)is the standard syntax for counting rows defined by SQL92 .NULLNULL

    • Description: count(*)It will count the rows whose value is NULL, but count(列名)will not count NULLthe rows whose value is this column.
  2. [Mandatory] count(distinct col) Calculate the NULLnumber of unique rows except for this column, note that count(distinct col1, col2)if one of the columns is all NULL, then even if the other column has a different value, it will be returned as 0.

  3. [Mandatory] When all the values ​​of a column are 0 NULL, count(col)the returned result is 0, but sum(col)the returned result is NULL, so sum()you need to pay attention to the NPEproblem when using it.

    • Positive example: The NPE problem of sum can be avoided by using:SELECT IF(ISNULL(SUM(g)),0,SUM(g)) FROM table;
  4. [Mandatory] Use ISNULL() to determine whether it is a NULL value.

    • Explanation: A direct comparison of NULL with any value is NULL.
      • The return result of NULL<>NULL is NULL, not false.
      • The return result of NULL=NULL is NULL, not true.
      • The return result of NULL<>1 is NULL, not true.
  5. [Mandatory] When writing the paging query logic in the code, if countit is 0, it should be returned directly to avoid executing the following paging statement.

  6. [Mandatory] Foreign keys and cascades must not be used, and all foreign key concepts must be resolved at the application layer.

    • Note: Take the relationship between students and grades as an example. The primary key in the student table is the foreign key student_idin the grades table . student_idIf the update in the student table student_idtriggers the student_idupdate in the grade table at the same time, it is a cascading update. Foreign keys and cascading updates are suitable for single-machine low concurrency, but not suitable for distributed, high-concurrency clusters; cascading updates are strong blocking, and there is a risk of database update storms; foreign keys affect the insertion speed of the database.
  7. [Mandatory] Prohibit the use of stored procedures, which are difficult to debug and extend, and have no portability.

  8. When correcting data (especially deleting and modifying records), it is necessary to selectavoid accidental deletion first, and then execute the update statement after confirmation.

  9. [Recommendation] Avoid the in operation if it can be avoided. If it cannot be avoided, you need to carefully evaluate the number of set elements behind in, and control it within 1000.

  10. [Reference] If there is a need for globalization, all characters are stored and represented in utf-8 encoding. Pay attention to the difference between character statistics functions.

    • illustrate:
      • SELECT LENGTH("Easy work"); returns 12
      • SELECT CHARACTER_LENGTH("Easy work"); returns 4
      • If you need to store expressions, then choose utf8mb4 for storage, pay attention to the difference between it and utf-8 encoding.
  11. [Reference] It TRUNCATE TABLEis DELETEfaster than , and uses less system and transaction log resources, but there TRUNCATEis no transaction and no trigger is triggered, which may cause accidents, so it is not recommended to use this statement in the development code.

    • Explanation: TRUNCATE TABLEFunctionally the same as a statement without a WHEREclause DELETE.

2. ORM mapping


  1. [Mandatory] In table query, never use * as the field list of the query, which fields must be clearly stated.

    • illustrate:
      • Increase query analyzer parsing cost.
      • Adding or subtracting fields is easy to be inconsistent with the resultMap configuration.
  2. [Mandatory] Boolean attributes of POJO classes cannot be added is, but database fields must be added is_, resultMapand mapping between fields and attributes is required.

    • Note: Refer to the definition of POJO classes and database field definitions, <resultMap>and it is necessary to add mappings in . 在MyBatis GeneratoThe code generated by r needs to be modified accordingly.
  3. [Mandatory] Do not use resultClassit as a return parameter. Even if all class attribute names correspond to database fields one by one, they need to be defined; conversely, each table must have one corresponding to it.

    • Description: Configure the mapping relationship to decouple the field from the DO class for easy maintenance.
  4. [Mandatory] Use the sql.xml configuration parameter: #{},#param#, do not use ${}this method is prone to SQL injection.

  5. [Mandatory] iBATIS The built-in one is queryForList(String statementName,int start,int size)not recommended.

    • Description: The implementation method is to get statementNameall the records of the corresponding SQL statement in the database, and then pass the subListfetched start,sizesubset.
    • Normal example:

      Map<String, Object> map = new HashMap<String, Object>();
      map.put("start", start);
      map.put("size", size);
  6. [Mandatory] It is not allowed to directly take HashMapAND Hashtableas the output of the query result set.

    • Description: resultClass=”Hashtable”, the field name and attribute value will be inserted, but the type of the value is uncontrollable.
  7. [Mandatory] When updating a data table record, the gmt_modifiedfield value corresponding to the record must be updated at the same time as the current time.

  8. [Recommendation] Don't write a large and comprehensive data update interface.

    • Passing in as a POJO class, whether it is your own target update field or not, is carried out update table set c1=value1,c2=value2,c3=value3;, which is wrong .
    • When executing SQL, do not update unchanged fields. One is error-prone; the other is low efficiency; the third is to increase binlog storage.
  9. [Reference] @TransactionalTransactions should not be abused.

    • Transactions will affect the QPS (Queries Per Second) of the database. In addition, where transactions are used, various rollback schemes should be considered, including cache rollback, search engine rollback, message compensation, and statistical correction.
  10. [Reference] <isEqual>is compareValuea constant that is compared with the attribute value, usually a number, which means that this condition is brought when it is equal;

    • <isNotEmpty>Indicates that it is executed when it is not empty and not null;
    • <isNotNull>Indicates that it is executed when the value is not null.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325567080&siteId=291194637