update数据库更新语句的时候,把表里所有的数据都更新了

经过来回的检查,发现是SQL语句没有加条件语句

修改前

	<update id="update">
			UPDATE smbms_user SET userCode=#{userCode},userName=#{userName},userPassword=#{userPassword},gender=#{gender},birthday=#{birthday},phone=#{phone},address=#{address},userRole=#{userRole},createdBy=#{createdBy},creationDate=#{creationDate},idPicPath=#{idPicPath}
		</update>

修改后

	<update id="update">
			UPDATE smbms_user SET userCode=#{userCode},userName=#{userName},userPassword=#{userPassword},gender=#{gender},birthday=#{birthday},phone=#{phone},address=#{address},userRole=#{userRole},createdBy=#{createdBy},creationDate=#{creationDate},idPicPath=#{idPicPath}
			WHERE id=#{id}
		</update>

测试类

		//更新
		User user=new User();
		user.setId(21);
		user.setUserCode("21");
		user.setUserName("lalaalall");
		int count=session.getMapper(userDao.class).update(user);

重点在于WHERE id=#{id}
没有加,那么表中的数据,都会变成你想加的那一条
在这里插入图片描述

但是这个更新,会把没有其余没有更新的其他值变为空
在这里插入图片描述
可修改SQL语句

		<update id="update">
		UPDATE smbms_user 
		<set>
			<if test="userCode!=null and userCode!=''">userCode=#{userCode},</if>
			<if test="userName!=null and userName!=''">userName=#{userName},</if>
			<if test="userPassword!=null and userPassword!=''">userPassword=#{userPassword},</if>
			<if test="gender!=null">gender=#{gender},</if>
			<if test="birthday!=null">birthday=#{birthday},</if>
			<if test="phone!=null and phone!=''">phone=#{phone},</if>
			<if test="address!=null and address!=''">address=#{address},</if>
			<if test="userRole!=null">userRole=#{userRole},</if>
			<if test="modifyBy!=null">modifyBy=#{modifyBy},</if>
			<if test="true">modifyDate=NOW(),</if>
			<if test="idPicPath!=null and idPicPath!=''">idPicPath=#{idPicPath},</if>
		</set>
		WHERE id=#{id}
		</update>
	User user = new User();
		user.setUserName("小杨过");
		user.setId(14);
		int count = session.getMapper(UserDao.class).update(user);

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章