1. 程式人生 > 實用技巧 >mybatis使用map傳遞引數與模糊查詢寫法

mybatis使用map傳遞引數與模糊查詢寫法

  前言:你有沒有遇到這種情況:當你使用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 = "%"#{value}"%"