接口中的参数传入map;
实现类的传入参数为map的键的名称,这个键可以自定义名称;
例:根据ID获取用户
接口:
//根据ID获取用户
User getUserById2(Mapmap);
接口实现类:
测试类:
@Test
public void getUserById2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap map = new HashMap<>();
map.put("userId",3);
User userById2 = mapper.getUserById2(map);
System.out.println(userById2);
sqlSession.commit();
sqlSession.close();
}
map传递参数,直接在sql取出key
对象传递参数,直接在sql中取出对象的属性
只有一个基本类型参数,不需要写parameterType
例:添加用户
接口:
int addUser2(Map map);
实现类:
insert into mybatis.user (id,name,pwd) values(#{userId},#{userName},#{passWord});
//userId,userName,passWord为map自定义键
测试类:
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap map = new HashMap<>();
map.put("userId",5);
map.put("userName","saf");
map.put("passWord","09090");
mapper.addUser2(map);
sqlSession.commit();
sqlSession.close();
}
模糊查询:
例:获取密码以4结尾的用户
接口:
//模糊查询
ListgetUserLike(String value);
实现类:
为了防止sql注入,like写为参数的形式。在java代码执行的时候,传递通配符%
测试类:
@Test
public void getUserLike(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List userLike = mapper.getUserLike("%4");
for (User user : userLike) {
System.out.println(user);
}
sqlSession.close();
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)