使用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","LiSy@163.com");

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM