java中map根據value獲取key,【狂神MyBatis筆記】map作為參數傳遞類型進行增刪改查模糊查詢

 2023-11-18 阅读 21 评论 0

摘要:接口中的參數傳入map; 實現類的傳入參數為map的鍵的名稱,這個鍵可以自定義名稱; 例:根據ID獲取用戶 java中map根據value獲取key?接口: //根據ID獲取用戶User getUserById2(Map<String,Object>map); 接口實現類: <select

接口中的參數傳入map;

實現類的傳入參數為map的鍵的名稱,這個鍵可以自定義名稱;

例:根據ID獲取用戶

java中map根據value獲取key?接口:

//根據ID獲取用戶User getUserById2(Map<String,Object>map);

接口實現類:

   <select id="getUserById2" parameterType="map" resultType="com.kuang.pojo.User">select * from mybatis.user where id=#{userId};//userId是自定義的鍵,用來作為id的參數</select>

測試類:

   @Testpublic void getUserById2(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);HashMap<String, Object> map = new HashMap<>();map.put("userId",3);User userById2 = mapper.getUserById2(map);System.out.println(userById2);sqlSession.commit();sqlSession.close();}

map傳遞參數,直接在sql取出key

對象傳遞參數,直接在sql中取出對象的屬性

java中map的遍歷。只有一個基本類型參數,不需要寫parameterType

例:添加用戶

接口:

int addUser2(Map<String,Object> map);

?實現類:

    <insert id="addUser2" parameterType="map">insert into mybatis.user (id,name,pwd) values(#{userId},#{userName},#{passWord});</insert>//userId,userName,passWord為map自定義鍵

java遍歷map的幾種方式?測試類:

   @Testpublic void addUser2(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);HashMap<String, Object> map = new HashMap<>();map.put("userId",5);map.put("userName","saf");map.put("passWord","09090");mapper.addUser2(map);sqlSession.commit();sqlSession.close();}

模糊查詢:

?

java獲取map的值。例:獲取密碼以4結尾的用戶

接口:

 //模糊查詢List<User>getUserLike(String value);

實現類:

  <select id="getUserLike" resultType="com.kuang.pojo.User">select * from mybatis.user where pwd like #{value}</select>

為了防止sql注入,like寫為參數的形式。在java代碼執行的時候,傳遞通配符%

測試類:

    @Testpublic void getUserLike(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);List<User> userLike = mapper.getUserLike("%4");for (User user : userLike) {System.out.println(user);}sqlSession.close();}

java遍歷map集合,

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/177452.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息