文章目录
1.MyBatis中map的应用
1.1.应用场景
假设,实体类,或者数据库中的表,字段或者参数过多,应当考虑使用Map!!!
2.2.具体实现
//万能map
int addUser2(Map<String,Object> map);
<!--对象中的属性,可以直接取出来 parameterType=传递map中的key-->
<insert id="addUser" parameterType="map">
insert into mybatis.user (id, name, pwd) values (#{userId},#{userName},#{passWord});
</insert>
@Test
public void addUser(){
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Map<String,Object> map = new HashMap<String,Object>();
map.put("userid",5);
map.put("userName", "Hello");
map.put("passWord","123456");
userMapper.addUser2(map);
sqlSession.commit();
}catch(Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
}
1.3.注意点!!!
- Map传递参数,直接在sql中取出key即可!【parameterType=“map”】
- 对象传递参数,直接在sql中取对象的属性即可!【parameterType=“Object”】
- 只有一个基本类型参数的情况下,可以直接在sql中取到! 多个参数用Map,或者注解!
2.模糊查询
User gteUserById(Map<String,Object> map);
<select id="getUserLike" resultType="com.pojo.User">
select * from mybatis.user where name like #{value}
</select>
@Test
public void getUserLike(){
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserLike("%lyh%");
for(User user : userList){
System.out.println(user);
}
}catch(Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
}