Bug一览:
数据库设计:
注意: status字段默认值为0
Mapper层接收的值:
注意: status=null
Order{orderId=null, userId=10001, routeId=3, majorNumber=1, childrenNumber=0, price=200, status=null}
此时Mapper的SQL:
<insert id="insert" keyProperty="orderId" useGeneratedKeys="true">
insert into order(user_id, route_id, status, major_number, children_number, price)
values (#{userId}, #{routeId}, #{status}, #{majorNumber}, #{childrenNumber}, #{price})
</insert>
存在的问题:
可以看出,status字段的值是null,而不是我想要的默认值0,这不就是bug嘛
分析Bug
经过测试发现
1)给数据库设有默认值的字段传啥值就是啥值(如上文的null)
2)不给status字段传值,那么它就是默认值0了
总结:
解决Bug
解决思路就是 如果字段为空就不给status传值 是不是就想到了 MyBatis的动态SQL啊
<insert id="insert">
insert into `order`
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="userId != null">
user_id,
</if>
<if test="routeId != null">
route_id,
</if>
<if test="status != null">
status,
</if>
<if test="majorNumber != null">
major_number,
</if>
<if test="childrenNumber != null">
children_number,
</if>
<if test="price != null">
price,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="userId != null">
#{userId},
</if>
<if test="routeId != null">
#{routeId},
</if>
<if test="status != null">
#{status},
</if>
<if test="majorNumber != null">
#{majorNumber},
</if>
<if test="childrenNumber != null">
#{childrenNumber},
</if>
<if test="price != null">
#{price},
</if>
</trim>
</insert>