"Java Development Manual"

First, the program statute (a) naming style

  1. [Mandatory] use Abstract abstract class name or the beginning of the Base; exception class named using ends Exception; test class named after the name of its class to be tested beginning to the end of the Test.

  2. [Mandatory] POJO class Boolean variables do not add the prefix is ​​otherwise resolved portion of the frame can cause serialization error. Description: build the table herein MySQL statute agreement first, whether or not the value of the expression is employed is_xxx naming, therefore, necessary to Set mapping from is_xxx to the xxx. Anti Example: is defined as the basic data types Boolean isDeleted property that the method is also isDeleted (), RPC frame when the reverse analysis, "mistake" is deleted corresponding to attribute names, attribute acquisition not cause, in turn thrown .

  3. [Reference] naming convention layers: A) Service / DAO layer naming convention method 1) a method of obtaining a single object with a prefixed get. 2) a method of obtaining a plurality of prefixed objects, such as the use forms plural ending list: listObjects. 3) obtain a statistical value of the method prefixed with count. 4) Insert method prefixed with save / insert. 5) method to remove prefixed with remove / delete. 6) using the modified method prefixed update. B) a domain model naming convention) data objects: xxxDO, xxx is the table name. 2) Data Transfer Object: xxxDTO, xxx is the name associated with the business. 3) display objects: xxxVO, xxx generally page name. 4) POJO is DO / DTO / BO / VO collectively prohibited named as xxxPOJO.

(C) code format

  1. [Mandatory] using 4 spaces to indent, prohibit the use of tab characters. Note: If you use the tab indentation, you must set a tab as four spaces. When IDEA setting tab is four spaces, do not check the Use tab character; while in eclipse, you must check the insert spaces for tabs. Positive Example: (1-5 points directed)
    public static void main (String [] args) {// indented four spaces String say = "hello"; // operator must be left a space int flag = 0; // must be a space between the brackets and the keyword if, f left bracket in parentheses, right bracket 0 and space is not required if (flag == 0) {System.out.println (say);} // left braces spaces before and do not wrap; after the opening brace to change the line if (flag == 1) {System.out.println ( "world"); // before the closing brace wrap, else there after the closing brace, do not wrap } else {System.out.println ( "ok" ); // directly after the end of the closing brace must wrap}}

(D) OOP Statute

  1. [Forced] to avoid such a static variable or static method to access, increase unnecessary analytical costs compiler, with direct access to the class name to a class of objects by reference.

  2. [Equivalent] determined force between the float, the basic data types can not be used to compare == packaging data types can not be determined with equals. Description: floating a "mantissa + exponent" encoding, similar to scientific notation "effective number + index" representation. Binary not accurately represent most decimal fractions

  3. [Force] To prevent loss of accuracy, prohibited constructor BigDecimal (double) manner into the double value BigDecimal object.

  4. On basic data types and data types of packaging used the following criteria: 1) [all] POJO class mandatory attributes must be packed data type. 2) [RPC] forcibly return value and parameters must be packed data type. 3) [Recommended] all local variables using the basic data types. Description: POJO class property is not the initial alert the user when needed, you must explicitly assign their own, NPE any questions or warehousing inspection, by the user to be guaranteed. Positive examples: database results may be null, because the automatic unpacking, with basic data types have to receive NPE risk. Counterexample: the total turnover of ups and downs such as display cases, that is plus or minus x%, x is the basic data types, called RPC service when the call is unsuccessful, the returned value is the default page displayed as 0%, which is unreasonable, It should be displayed as the scribe line. So Packaging data type null value can represent additional information, such as: remote call fails, quit unexpectedly.

  5. [Mandatory] POJO class must write toString method. Use the IDE tools: source> When generate toString, if inherited another POJO class, pay attention to add about super.toString in front. Description: When performing the method throws an exception, can directly call toString POJO () method of printing attribute values, easy to troubleshoot.

  6. [Force] POJO class is prohibited while the presence of the corresponding property isXxx xxx () and getXxx () method. Description: The frame extraction method call xxx property, and can not determine which method must have been a prior call to.

  7. When [Recommended] to access the array using an index with the split method of the String obtained, there is no content checking to be done after the last delimiter, otherwise there will be risk IndexOutOfBoundsException is thrown. Description: String str = "a, b, c ,,"; String [] ary = str.split ( ","); // 3 is greater than expected, the result is 3 System.out.println (ary.length);

  8. [Recommended] circular body, connection strings, using the StringBuilder append extension method. Description: In the following example, decompile the byte code files are displayed for each cycle a new StringBuilder object, then append operation, and returns the String object using the toString method, resulting in a waste of memory resources. Anti Example: String str = "start"; for (int i = 0; i <100; i ++) {str = str + "hello";}

  9. [Recommended] can be declared final class, member variables, methods, and local variables, the following final keyword: 1) does not allow inherited class, such as: String class. 2) not allowed to modify the domain object references. 3) is not allowed to override methods, such as: setter method POJO class. 4) Local variables are not allowed to run in the process of re-assignment. 5) Avoid repeated use of a context variable, you can be forced to re-use final define a variable, to facilitate better reconstruction.

  10. [Recommended] caution Object clone method to copy objects. Note: The default method is to clone the object shallow copy, are to achieve the depth required to traverse a deep copy the copy-implemented method clone override domain objects.

  11. [Recommended] class members and strict access control methods: 1) If not directly create an external objects through new, then the constructor must be private. 2) tools have allowed public or default constructor. 3) class of non-static member variables and shared with subclasses, must be protected. 4) class non-static member variables and only use this type must be private. 5) If the class static member variables in this class use only, must be private. 6) If the static member variables to consider whether the final. Internal 7) class method only for class members to call, must be private. 8) class member method only public inheritance class, then the limit is protected.

(E) the collection process

  1. [Mandatory] hashCode and equals with regard to the processing of the following rules: 1) as long as the override equals, you must override hashCode. 2) are not stored because the Set duplicate objects, is determined by their hashCode and equals, so the object is stored Set must override these two methods. 3) If the custom objects as Map keys, you must override hashCode and equals. Description: String hashCode and equals method has been overwritten, so we can happily use a String object to use as a key.

  2. [Forced] when using the Map method keySet () / values () / entrySet () returns a collection of objects, can not be adding elements to operate, otherwise it will throw an UnsupportedOperationException exception.
    Description: entrySet () and has key value, delete it directly into the element or elements of the method are invalid. keySet () there key, can operate on the key, so it can be used remove () and equals (), it returns true.
    values () only value in value, there is no key, value value is of no use, so the values () method is only convenient to get all the value value.

  3. [Object] Collections class forced return, such as: emptyList () / singletonList () are all immutable list, can not be added or deleted element operation. Counterexample: If no query results returned Collections.emptyList () empty collection object, the caller Once the operation added elements, will trigger an UnsupportedOperationException.

  4. [Mandatory] in subList scene, pay attention to the height of the original collection of elements to add or remove, will lead to traverse the sub-lists, add, delete produce ConcurrentModificationException exception.
    Positive Example: String [] = sList.toArray SIDS (new new String [sList.size ()]);
    List list = new ArrayList<>(2); list.add("guan"); list.add("bao"); String[] array = list.toArray(new String[0]);

Description: toArray parameterized using a method, the array size of the space length: 1) equals 0, dynamically create the same size array, the best performance. 2) size is greater than zero but less than, equal to recreate the size of the array size, increasing the burden on GC.
Java Development Manual
12/44
3) equal size, under high concurrency, after array creation is complete, the case size is larger, the negative impact on the same. 4) is greater than the size, wasted space, and the size of the inserted null value, the presence of hidden NPE.

Anti Example: String [] array = (String []) list.toArray (); running, given

  1. [Force] using tools Arrays.asList () array into a set of time, which can not be used to modify a set of related methods, it add / remove / clear method throws an UnsupportedOperationException. Description: asList returns the class object is an internal Arrays, and does not implement the modification method set. Arrays.asList embodies the adapter mode, only conversion interface, back-end data remains array. String [] str = new String [] { "yang", "hao"}; List list = Arrays.asList (str); The first case: list.add ( "yangguanbao"); runtime exception. Second case: str [0] = "changed"; modified too, and vice versa.

  2. [Mandatory] generic wildcard <? Extends T> to receive the data returned, the wording of this generic collections can not use the add method, and <? Super T> get method can not be used as an interface call assignment when error-prone.
    Description:
    the extends may be used to define the return type, argument types can not be used to define (in other words:? Extends xxx only defines a method return type, able to determine the minimum JDK boundaries inherited such as XXX, as long as the parent of the class class can receive, but can not determine the specific type of parameters passed, can only accept incoming null).
    can be used to define the type of super parameters, it can not be used to define the type of return (in other words:? supper xxx only for parameter passing method, since incoming jdk can be determined as a subclass xxx, receiving only return the Object class).
    ? Neither method for passing parameters, can not be used in the method returns.

  3. [] Do not force the elements remove / add operations in the foreach loop. remove elements, use Iterator way, if concurrent operations, the need for Iterator object locking.

Positive examples:
List list = new ArrayList<>();
list.add("1");
list.add("2");
Iterator = list.iterator iterator ();
the while (iterator.hasNext ()) {
String = Iterator.next Item ();
IF (condition remove elements) {
the Iterator.remove ();
}
}
calls the iterator deletion method:
1. first check set
2. remove the element
index position of the cursor element reassignment 3.
4. check the re-assignment parameter set

Counter-example:
for (String Item: List) {
IF ( "1" .equals (Item)) {
list.remove (Item);
}
}
Summary: If we remove the elements we use foreach happens to be the last one before deleting completed under a cursor element in the position index is just equal to the length size of the set size. However, after the completion of deleting the number size minus 1, but the cursor does not change. Results in unequal next cycle continues downward, resulting in the array does not pass inspection, throw java.util.ConcurrentModificationException

  1. [Mandatory] in JDK7 version and above, Comparator implementation class to meet the following three conditions, or Arrays.sort, Collections.sort will throw IllegalArgumentException. Description: the following three conditions 1) x, y, and a comparison result comparison result y, x is the opposite. 2) x> y, y> z, then x> z. 3) x = y, then x, z comparison result and y, z the same comparison result.
    Anti Example: The following example is not equal to the process, the exchange of two objects are not reciprocal determination result does not meet the first condition, in practical use
    may be abnormal.
    new Comparator () {
    @Override
    public int compare(Student o1, Student o2) {
    return o1.getId() > o2.getId() ? 1 : -1;
    }
    };

    15. 【推荐】使用 entrySet遍历 Map类集合 KV,而不是 keySet方式进行遍历。 说明:keySet 其实是遍历了2 次,一次是转为 Iterator 对象,另一次是从 hashMap 中取出key所对应 的 value。而entrySet 只是遍历了一次就把 key和value 都放到了 entry中,效率更高。如果是 JDK8, 使用 Map.forEach 方法。

    Positive Example: values ​​() Returns the value of V is set, a list is a collection of objects; keySet () Returns the value of K is set, Set is a set of objects; the entrySet () returns the value of KV combination set.

  2. [Reference] rational use of orderliness (sort) and good stability of the set (order), to avoid the negative effects of the disorder collections (unsort) and instability (unorder) brings. Description: ordering means is traversed by the result of some kind of comparison rules arranged in order. Stability refers to a collection of elements each traversal order is constant. Such as: ArrayList is the order / unsort; HashMap is unorder / unsort; TreeSet is order / sort.

  3. [Reference] Set of elements with a unique characteristic, you can quickly go to a set of re-operation, to avoid the use of List contains traversing method, compared to retry.

(Vi) concurrent processing

  1. [Mandatory] thread resources must be provided by the thread pool, do not allow yourself to explicitly create threads in the application. Description: The benefits of the thread pool is to reduce the overhead in creating and destroying threads consumed time and system resources, to solve the problem of insufficient resources. If you do not use the thread pool, it may cause the system to create a large number of similar threads lead consumed or memory problem "excessive handover".

  2. [Mandatory] thread pool Executors are not allowed to create, but by ThreadPoolExecutor way, this approach allows the students to write more explicit operating rules thread pool, to avoid the risk of resource depletion. Description: Executors drawbacks thread pool objects returned as follows: 1) FixedThreadPool and SingleThreadPool: request queue length allowed Integer.MAX_VALUE, may accumulate a large number of requests, thereby causing OOM. 2) CachedThreadPool: allow the number of threads to create Integer.MAX_VALUE, may create a large number of threads, resulting OOM.

  3. [Mandatory] SimpleDateFormat is not thread-safe class, usually not defined as a static variable, if defined as static, must be locked, or use DateUtils tools. Positive examples: Note thread-safe, use DateUtils. Also recommend the following process: private static final ThreadLocal df = new ThreadLocal () {@Override protected DateFormat initialValue () {return new SimpleDateFormat ( "yyyy-MM-dd");}}; Description: If an application is JDK8, may be used instead of Instant Date, LocalDateTime instead of Calendar, DateTimeFormatter instead of the SimpleDateFormat, official explanation given: simple beautiful strong immutable thread-safe.

  4. [Mandatory] must be recovered ThreadLocal variable custom, especially in the thread pool scene, threads often be reused, if you do not clean up ThreadLocal variable custom, may affect subsequent business logic and cause memory leaks and other problems. Make use of try-finally block agent recovered. Positive Example: objectThreadLocal.set (userInfo); try {// ...} finally {objectThreadLocal.remove ();}

  5. When [forced] high concurrency, synchronous call should go to loss of performance considerations lock. Lock-free data structures can be used, do not use locks; lock can block, do not lock the entire method body; can lock an object, do not use class lock. Description: code blocks as much as possible for locking the workload as small as possible to avoid call RPC method in the lock block

  6. After [compulsory] in the way of using the block waiting to acquire the lock must be outside the try block, and there is no method might throw an exception of calls between the locking method and try code block, to avoid locking the success in finally It can not be unlocked. Description A: If the method between the lock and try code block method invocation throws an exception, it can not be unlocked, causing other threads can not obtain a lock. Description 2: If the lock method in the try block, the exception may be thrown due to other methods, resulting in a finally block, UNLOCK unlocking an unlocked object, it calls the method tryRelease AQS (depending on the implementation class ), IllegalMonitorStateException throws an exception. Description Three: In the process of realization lock Lock object may throw unchecked exceptions, the consequences of the same titanium Description

  7. [To force] in the way of the use of mechanisms to try to acquire the lock, the code block before entering the business, you must first determine whether the current thread holds the lock. The same rules and release the lock of lock blocking standby mode. Description: unlock method Lock object is executed, it will call tryRelease method of AQS (depending on the specific implementation class), if the current thread does not hold a lock, throwing IllegalMonitorStateException exception.

  8. When [forced] concurrently modify the same record, avoid lost updates, need to lock. Either at the application level locking, or locked in the cache, or use optimistic locking at the database level, using the updated version as a basis. Note: If the collision probability is less than 20% per visit is recommended to use optimistic locking, otherwise use pessimistic locking. The number of optimistic locking retry not less than 3 times.

  9. [Forced] multi-threaded parallel processing timed task, when Timer running multiple TimeTask, as long as one does not catch exceptions thrown, other tasks will automatically terminate, if ScheduledExecutorService in dealing with the timing of the task is not the problem.

  10. [Recommended] CountDownLatch using asynchronous transfer synchronization, each thread must call countDown method before exiting, note the code execution thread catch exception ensure countDown method is executed to avoid the main thread was unable to await execution method, until the timeout to return results. Note: Note that child thread throws an exception stack, not to the main thread try-catch.

  11. [Recommended] Random instance is to avoid the use of multiple threads, although sharing the instance is thread-safe, but due to competing for the same seed performance deterioration. Description: Random includes instances java.util.Random or Math.random () manner. Positive examples: After JDK7, can directly use API ThreadLocalRandom, but before JDK7, need to be coded to ensure that each thread holds an instance.

  12. [Recommended] in concurrency scenarios, optimize risk lazy initialization problem by double-checking the lock (double-checked locking) (refer to The "Double

  13. [Reference] volatile memory to solve the multi-threaded invisible problem. For a write once read many, synchronization problems can be solved variables, but if you write, the same can not solve thread safety issues. Note: If the operation is a count ++, implemented using the following categories: AtomicInteger count = new AtomicInteger (); count.addAndGet (1); if JDK8, recommended LongAdder object AtomicLong performance better than (optimistic locking reduce the number of retries) .

  14. [Reference] HashMap be resize when capacity is insufficient due to high concurrency dead links may occur, leading to soaring CPU, can be used in the development process other data structures or locked to avoid this risk.

  15. [Reference] ThreadLocal object using the static modification, ThreadLocal can not solve the problem of shared update objects. Description: This variable is for all operations within a thread shared, set to a static variable, all such instances share the static variables, that is to say in class is used to load the first time, allocates only a storage space, all this object class (as long as it is defined in this thread) can manipulate the variables.

(Vii) control statements

  1. [Force] When the variable type is String in parentheses switch and when the variable external parameters, must first be determined null.

  2. [Mandatory] in high concurrency scenarios, avoid the use of "equal" conditions as the judge interrupted or exit. Note: If no handle concurrency control, determination is likely to occur where equivalent "breakdown", the use of larger or smaller than the interval determination condition in place. Anti Example: determining the number of prizes remaining equal to zero, the termination payment of prizes, but because the number of concurrent processing errors become negative instant prizes, so, the activities can not be terminated.

(H) of the Statute comment

  1. [Reference] special comment tags, please indicate the mark of man and mark time. Note that the timely processing of these markers by marking the scan, frequent cleaning of such marks. Sometimes the fault line is derived from the code at these marks. 1) Do (TODO) :( person mark, mark time, [estimated processing time]) the need to achieve, but has yet to achieve the function. This is actually a Javadoc tag, the current Javadoc not yet implemented, but has been widely used. It can be applied to classes, interfaces and methods (because it is a Javadoc tag). 2) mistake, does not work (FIXME) :( person mark, mark time, [estimated processing time]) labeled with a code in comments FIXME is wrong and does not work, the situation needs to be corrected in time.

(Ix) Other

  1. [Note] forced Math.random () This method returns a double type, attention range of values ​​0≤x <1 (to a zero value can be taken, in addition to zero exception noted), if you want to acquire the random number integer type, do not x is then enlarged several times rounding 10, directly or nextLong nextInt Random object method.

Second, the exception log
(a) Exception Handling

  1. [There are] forced into the try block transaction code after the catch exception if need to roll back the transaction, must pay attention to manually roll back the transaction.

  2. [Mandatory] must finally blocks resource object, stream object is closed, there is an exception have to do try-catch. Note: If JDK7 and above, can use the try-with-resources way.

  3. [Mandatory] Do not use the return in the finally block. Description: try block return statement after the successful execution does not return immediately, but continue finally statement in the block, if there is a return statement here, then return to this direct, ruthless discarded the return point in the try block.

  4. [Recommended] prevent NPE, the basic training programmers, attention NPE generated scene: 1) return type of basic data types, the object is packaged return data type, may occur automatically unpacking NPE. Anti Example: public int f () {return Integer} objects, if null, automatic polishing solution tank NPE. 2) database results may be null. 3) Even if the elements of the collection isNotEmpty, fetched data elements may be null. 4) When the remote call returns an object, all require a null pointer is determined to prevent the NPE. 5) The acquired data Session, NPE recommended inspection, to avoid a null pointer. 6) cascade call obj.getA () getB () getC ();.. A series of calls, easy to produce NPE. Example n: Optional use of Class JDK8 NPE to prevent problems.

(B) of the Statute of the log

  1. [Forced] to avoid duplication of print logs, wasted disk space, be sure to set additivity = false in log4j.xml in. Positive examples:

  2. [Recommended] carefully logging. Production environment disable output debug log; selectively output info log; if a warn to record business behavior when just on the line information, be sure to pay attention to the log output problems, avoid server disk explode, and remember to delete these observations logs . Description: The log output is not massive, is not conducive to system performance, is not conducive to quickly locate the point of error. Consider recording logs: These logs anyone really see it? See this log what can you do? You can bring benefits to troubleshooting?

  3. [Recommended] warn log level can be used to record the user input parameter error, to avoid customer complaints when, at a loss. If not necessary, do not play error level in this scenario, to avoid frequent alarms. Description: Note-level log output, error logging system level only logical errors, anomalies or significant error messages.

  4. [Recommended] try to describe the log error messages in English, if the error message logs described in English unintelligible words to describe the use of Chinese, or prone to ambiguity.

Third, unit testing

  1. [Forced] a good unit tests must comply with the principle of AIR. Description: When running the unit tests online, feels like air (AIR) as does not exist, but in the quality assurance testing, but it is very critical. On a good unit test macro level, with automated, independence, characteristics can be repeated.
    ⚫ A: Automatic (Automation)
    ⚫ the I: work of the Independent (independent)
    ⚫ R & lt: Repeatable (repeat)

  2. [Recommended] to write unit test code compliance BCDE principle, in order to ensure the delivery of quality test module.
    ⚫ B: Border, boundary value tests, including cyclic boundary, special values, specific time point, the data sequence and the like.
    ⚫ C: Correct, correct input, and the results expected.
    ⚫ D: Design, combined with the design documents to write unit tests.
    ⚫ E: Error, forced error input (eg: illegal data, exception process, allowing traffic outside the like), and the expected results.

  3. [Reference] In order to more easily unit test, to avoid the following service code:
    ⚫ constructor to do too much.
    There are too many global variables and static methods ⚫.
    ⚫ there are too many external dependencies.
    ⚫ there is too much of a conditional statement. Description: Multilayer recommend the use of conditional statements Wei statement, strategy pattern, state pattern, etc. reconstruction.

Fourth, security statute

  1. [Mandatory] is part of the user's personal page or access control functions must be checked. Note: do not prevent the level of permissions you can check random access, modify, delete other people's data, such as viewing the contents of private messages to others, modify the order of others.
  2. [Mandatory] prohibits direct user sensitive data show, you must desensitization to display data. Description: Mainland China appears as a personal cell phone number: 137 **** 0969, hidden among four, to prevent loss of privacy.
  3. [Force] SQL user input parameters or parameter binding METADATA rigorous use of field values ​​is defined, to prevent SQL injections, prohibiting access to the database SQL string concatenation.
  4. [Mandatory] user requests any parameters passed validation must be done.
  5. Description: Ignore parameter calibration may result in: ⚫
    Page size is too large ⚫ memory overflow results in order by malicious database query slow to redirect any ⚫ ⚫ ⚫ SQL injection deserialization injection ⚫ regular input source string ReDoS denial of service
    Description: Java code with the regular client to validate the input, some regular written verification ordinary user input is no problem, but if the attacker to use a specially constructed to validate the string, the result may lead to an endless loop.

  6. [Force] In use the platform resources, such as text messages, e-mail, telephone, orders, payment, must implement a mechanism preventing correct reproduction, such as limiting the number of fatigue degree control, parity codes, to avoid excessive capital resulting brush damage. Description: send such registration verification code to your phone, if not limit the number and frequency, you can use this feature to harass other users, SMS platform and causing a waste of resources.

Five, MySQL database
(a) Statute of the construction of the table

  1. Forced expression of [] 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 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.

  2. [Mandatory] decimal type is decimal, prohibit the use of float and double.

  3. [Varchar] mandatory 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 other fields efficiency index.

  4. [Mandatory] table must have three fields: id, create_time, update_time.

(B) of the Statute of the index

  1. [Force] fields having unique operational characteristics, 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.
  2. [Mandatory] prohibits more than three tables 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.
  3. [Mandatory] indexing on varchar fields, 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.

  4. [Mandatory] 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.

  5. [Recommended] 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 counter-example: If there is an index range query, the index orderliness can not use, such as: WHERE a> 10 ORDER BY b; a_b can not sort the index.

  6. [Recommended] 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.

  7. [Recommended] or using the delay associated with the sub-query optimization over more scene paging.
    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 Example: id to quickly locate the segment needs to be acquired, then the association:. SELECT a * FROM Table 1 a, (select id from Table 1 where conditions LIMIT 100000,20) b where a.id = b.id

(C) SQL statements

  1. [Mandatory] Do not use the count (column name) or count (constant) instead of count ( ), count ( ) syntax is the number of rows SQL92 standard statistical definition, has 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.

  2. [Force] count (distinct col) calculates the number of columns is not repeated rows other than NULL, the note count (distinct col1, col2) If a whole is NULL, then even if another row have different values, but also returns to zero.

  3. [Mandatory] When the value of a column of all time NULL, count (col) returns a value of 0, but the sum (col) returns a value of NULL, so using sum () takes note NPE problem. Positive Example: Use a manner to avoid problems NPE sum of: SELECT IFNULL (SUM (column), 0) FROM table;

  4. [Force] 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.

  5. [Forced] write code paging query logic, if the count is zero should be returned directly to avoid the implementation of pagination statement back.

  6. [] Shall not be used to force a 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.

  7. [Mandatory] prohibit the use of stored procedures, stored procedures, difficult to debug and extend, and no portability.

  8. When [mandatory] data revision (in particular, delete, modify recording operation), first select, to avoid accidentally deleted, confirmation in order to perform the update statement.

  9. [Recommended] 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

(D) ORM mapping

  1. [] Do not use force when resultClass 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.

  2. [Mandatory] sql.xml configuration parameters: # {}, # param # Do not use $ {} in this way is prone to SQL injection.

  3. [Mandatory] are not allowed to take a direct output 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.

Guess you like

Origin www.cnblogs.com/chen-chen-chen/p/11621803.html