SpringBoot+MyBatis實現(xiàn)動態(tài)字段更新的三種方法
在Spring Boot和MyBatis中,實現(xiàn)動態(tài)更新不固定字段的步驟如下:
方法一:使用MyBatis動態(tài)SQL(適合字段允許為null的場景)
定義實體類
包含所有可能被更新的字段。
Mapper接口
定義更新方法,參數(shù)為實體對象:
void updateUserSelective(User user);
XML映射文件
使用<set>
和<if>
動態(tài)生成SQL:
<update id="updateUserSelective" parameterType="User"> UPDATE user <set> <if test="name != null">name = #{name},</if> <if test="age != null">age = #{age},</if> <if test="address != null">address = #{address},</if> <if test="phone != null">phone = #{phone},</if> </set> WHERE id = #{id} </update>
注意:此方法無法將字段更新為null
,因為參數(shù)為null
時條件不成立。
方法二:使用Map和字段過濾(支持字段更新為null)
Service層過濾字段
在Service中定義允許更新的字段,并過濾請求參數(shù):
public void updateUser(Long id, Map<String, Object> updates) { Set<String> allowedFields = Set.of("name", "age", "address", "phone"); updates.keySet().retainAll(allowedFields); // 過濾非法字段 userMapper.updateUserSelective(id, updates); }
Mapper接口
使用Map接收動態(tài)字段:
void updateUserSelective(@Param("id") Long id, @Param("updates") Map<String, Object> updates);
XML映射文件
動態(tài)生成更新語句:
<update id="updateUserSelective"> UPDATE user <set> <foreach collection="updates" index="key" item="value" separator=","> ${key} = #{value} </foreach> </set> WHERE id = #{id} </update>
注意:使用${key}
存在SQL注入風險,需在Service層嚴格過濾字段名。
方法三:使用@UpdateProvider(靈活且安全)
定義SQL提供類
動態(tài)構建安全SQL:
public class UserSqlProvider { public String updateSelective(Map<String, Object> params) { Long id = (Long) params.get("id"); Map<String, Object> updates = (Map<String, Object>) params.get("updates"); Set<String> allowedFields = Set.of("name", "age", "address", "phone"); StringBuilder sql = new StringBuilder("UPDATE user SET "); allowedFields.forEach(field -> { if (updates.containsKey(field)) { sql.append(field).append(" = #{updates.").append(field).append("}, "); } }); sql.setLength(sql.length() - 2); // 移除末尾逗號 sql.append(" WHERE id = #{id}"); return sql.toString(); } }
Mapper接口
使用@UpdateProvider注解:
@UpdateProvider(type = UserSqlProvider.class, method = "updateSelective") void updateUserSelective(@Param("id") Long id, @Param("updates") Map<String, Object> updates);
優(yōu)點:避免SQL注入,動態(tài)生成安全語句。
總結
方法一適合簡單場景,字段無需設置為
null
。方法二靈活,需嚴格過濾字段。
方法三推薦用于生產環(huán)境,安全且維護性強。
根據(jù)需求選擇合適方案,確保字段更新的靈活性和安全性。
到此這篇關于SpringBoot+MyBatis實現(xiàn)動態(tài)字段更新的三種方法的文章就介紹到這了,更多相關SpringBoot MyBatis字段更新內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring Boot 深入分析AutoConfigurationImportFilter自動化條件
這篇文章主要分析了Spring Boot AutoConfigurationImportFilter自動化條件配置源碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2022-07-07springmvc圖片上傳及json數(shù)據(jù)轉換過程詳解
這篇文章主要介紹了springmvc圖片上傳及json數(shù)據(jù)轉換過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-10-10Springboot使用maven打包指定mainClass問題
這篇文章主要介紹了Springboot使用maven打包指定mainClass問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04