Map和模糊查詢
在某些時候我們只需要給MyBatis傳遞幾個參數而不是一個完整的對象,如僅僅update表中的兩三個屬性。此時parameterType設置為一個pojo顯然不合適。可以考慮使用Map
mapper.xml
<update id="updateName" parameterType="map">
# 使用map傳遞參數在sql中直接取出key即可
update mybatis.employee
set last_name=#{last_name},
email=#{email}
where empid = #{empid}
</update>
//接口
int updateName(Map map);
測試類
@Test
public void test2(){
SqlSession sqlSession = MyBatisUtil.getSqlSession();
EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
Map<String ,String> map= new HashMap();
map.put("empid","1002");
map.put("last_name","李商隱");
map.put("email","LiSy@163.com");
empMapper.updateName(map);
sqlSession.commit();
sqlSession.close();
}
模糊查詢例子
-
mapper.xml
<select id="getEmpListByName" resultType="com.maple.pojo.Employee"> select * from mybatis.employee where last_name like #{value} </select>
-
j接口
List<Employee> getEmpListByName(String value);
-
測試類
@Test public void test3(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(); EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class); List<Employee> list = empMapper.getEmpListByName("%李%"); for(Employee employee : list){ System.out.println(employee); } sqlSession.commit(); sqlSession.close(); }