Skip to content

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 field text. (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)

SELECT * from user where userName = ${userName}
translates into this
SELECT * from user where userName = Ted
, but (#{} - equivalent to PreparedStatement in JDBC)
SELECT * from user where userName = #{userName}
translates into
SELECT * from user where userName = ?
, then assign Ted with single quote to replace ?
SELECT * from user where userName = 'Ted'
So the best usage would be
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]

💡 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.

💡 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.

💡 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.