前言:你有沒有遇到這種情況:當你使用mybatis修改表數據時,你只想改動幾個字段,但是你的實體類封裝的數據太多了,有上百條數據,
你若是創建這么一個實體類,那么真的要折騰死人。有沒有什么辦法只傳遞幾個你想要的數據呢?下面來看看這種使用map傳值的方式:
數據庫有這么一個表student且數據只有一條:
你現在想把這條數據中的sname改為王雲雲,sgender改為女。
先在對應的Mapper接口中編寫方法updateById():
public int updateById(Map<String,Object> map);
在對應的Mapper.xml中綁定參數並編寫sql:
<update id="updateById" parameterType="map"> update mybatis.student set sname=#{sname},sgender=#{sgender} where id = #{id}; </update>
寫相應的java代碼進行修改的測試:
@Test public void updateById(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); Map<String,Object> map = new HashMap<String,Object>(); map.put("sname","王雲雲"); map.put("sgender","女"); map.put("sid","1001"); userMapper.updateById(map); sqlSession.commit(); sqlSession.close();
}
運行測試代碼並查看結果:
修改成功!
mybatis中如何寫模糊查詢避開sql注入?
1、java代碼執行的時候傳遞通配符%%:
mapper.getUser("%王%");
2、sql拼接時就使用通配符:
select * from user where name like "%"#{value}"%"