ORM Guideline
ORM Rules ¶
Specific column names should be specified during query, rather than using * - [Mandatory] ¶
(1)
*increases parsing cost and its redundant field may rise network consumption, especially the fieldtext. (2) It may introduce mismatch with resultMap when adding or removing query columns.
xml <select id="SelectPerson" parameterType="int" resultMap="PersonResultMap"> SELECT id, name, address FROM PERSON WHERE id = #{id} </select>
Use \<resultMap> as return parameters corresponding DO definition is needed - [Mandatory] ¶
Mapping configuration is needed, to decouple DO definition and table columns, which in turn facilitates maintenance.
<resultMap type="Person" id="PersonResultMap"> <id property="id" column="ID"/> <result property="name" column="NAME"/> <result property="address" column="ADDRESS"/> </resultMap>
Use #{}, #param# instead of ${} with parameters in xml configuration - [Mandatory] ¶
![]()
${}. SQL injection may happen in this way.
When Mybatis processes#{}, it will replace#{}in sql with ?, then call PreparedStatement to assign value.
When Mybatis processes${}, it will just call Statement to assign${}with value.This (
${}- simple variable)translates into thisSELECT * from user where userName = ${userName}, but (SELECT * from user where userName = Ted#{}- equivalent to PreparedStatement in JDBC)translates intoSELECT * from user where userName = #{userName}, then assign Ted with single quote to replace ?SELECT * from user where userName = ?So the best usage would beSELECT * from user where userName = 'Ted'SELECT * from ${tableName} where userName = #{userName}
Do not use HashMap as DB query result type - [Mandatory] ¶
resultType="HashMap". If the value corresponds to its field is empty, then this field will be ignored directly when mapping to a HashMap.
gmt_modified column should be updated with current timestamp simultaneously with DB record update - [Mandatory] ¶
Name of Boolean property of POJO classes is should not be prefixed with is, while DB column name should prefix with is - [Recommended] ¶
Refer to rules of POJO class and DB column definition, mapping between properties and columns is needed in \<resultMap>. Code generated by MyBatis Generator might need to be adjusted.
Update only related columns in the DB table - [Recommended] ¶
Do not define a universal table updating interface, which accepts POJO as input parameter, and always update table set c1=value1, c2=value2, c3=value3, ... regardless of intended columns to be updated. It is better not to update unrelated columns, because it is error prone, not efficient, and increases binlog storage.
Do not overuse @Transactional - [Recommended] ¶
Because transaction affects QPS of DB, and relevant rollbacks may need be considered, including cache rollback, search engine rollback, message making up, statistics adjustment, etc.