The mybatis query field is an operation where null is set to 0

  • 2021-08-21 20:32:54
  • OfStack

Background

When using an mybatis query (mysql), multiple double fields are used for addition, but several of these fields may be null, throwing a null pointer.

Solution

The automatically generated mybatis mapper file looks like this


<sql id="Base_Column_List">
 ID, PREPAYMENT_FEE
 </sql>

Modify it


<sql id="Base_Column_List">
 ID, ifnull(PREPAYMENT_FEE,0) as PREPAYMENT_FEE
 </sql>

Supplement: Dealing with the relationship between 0 and null in mybatis

Recently, in the project development, mybatis encountered a very strange problem, because it wanted to pass an int type 0 into the data in the background, but it was recognized as null.

Later, when troubleshooting the problem, it is found that mybatis source code has forced its definition.

Therefore, to solve the problem, we can transform the mybatis source code, or simply do the following processing:


<insert id="insertDemo" parameterType="java.util.Map">
INSERT INTO
 TABLE
<trim prefix="(" suffix=")" suffixOverrides=",">
 <if test="importRow != null and importRow != '' or importRow ==0 ">
 IMPORT_ROW,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
 <if test="importRow != null and importRow != '' or importRow ==0 ">
  #{importRow},
 </if>
</trim>
</insert>

Enhanced Judgment Add or importRow = = 0


Related articles: