使用Map和模糊查询

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","[email protected]");

		empMapper.updateName(map);

		sqlSession.commit();
		sqlSession.close();

	}

模糊查询例子

  1. mapper.xml

        <select id="getEmpListByName" resultType="com.maple.pojo.Employee">
            select *
            from mybatis.employee
            where last_name like #{value}
        </select>
    
  2. j接口

    	List<Employee> getEmpListByName(String value);
    
  3. 测试类

    	@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();
    
    	}
    
    

猜你喜欢

转载自www.cnblogs.com/junlinsky/p/12810625.html