如何实现MyBatis仅更新SQL语句中指定的字段?
// 对象
public class Entity {
private String id = null;
private int value = null;
private Timestamp createTime = null;
// getter and setter ...
}
// 数据表
CREATE TABLE qai_entity (
id CHAR(10) NOT NULL,
value INT NOT NULL DEFAULT 0,
create_time TIMESTAMP NOT NULL,
PRIMARY KEY (id)
)
// MyBatis 配置
<resultMap id="entityResultMap" type="Entity">
<result property="id" column="id" />
<result property="value" column="value" />
<result property="createTime" column="cre_tim" />
</resultMap>
<select id="findEntityById" parameterType="java.lang.String" resultMap="entityResultMap">
SELECT * FROM qai_entity WHERE id = #{id}
</select>
<update id="updateValueById_1" parameterType="Entity">
UPDATE qai_entity
<set>
<if test="value != null">value = #{value},</if>
<if test="createTime != null">create_time = #{createTime},</if>
</set>
WHERE id = #{id}
</update>
<update id="updateValueById_2" parameterType="Entity">
UPDATE qai_entity SET value = #{value} WHERE id = #{id}
</update>
// 调用
Entity dbEntity = entityDao.findEntityById("id-001"); // 调用配置文件中的查询SQL语句
Entity entity = new Entity();
entity.setValue(dbEntity.getValue() + 1);
entityDao.updateValueById(entity);
public int updateValueById(Entity entity) {
... ...
update("updateValueById_1", entity); // 调用配置文件中的更新SQL语句
}
以上是所有配置和使用的简要介绍。
在以上情况中,无论是调用updateValueById_1或updateValueById_2,MyBatis都会把CreateTime一并更新到当前的数据库时间。当然,这里只有简单的两三个字段,为的是看起来简单些。在实际情况下往往还有其他字段,且这些字段在建表时也设置了默认值,MyBatis也会一并更新为默认值。这说明Mybatis是在做全表更新。
请问如何实现MyBatis仅更新SQL语句中指定的字段?