1.通过parameterType指定输入参数的类型,类型可以是简单类型、hashmap、pojo的包装类型;
2.传递pojo的包装对象
完成用户信息的综合查询,需要传入查询条件很复杂(可能包括用户信息、其它信息,比如商品、订单的),针对这个需求,建议使用自定义的包装类型的pojo,在包装类型的pojo中将复杂的查询条件包装进去。po是持久层的对象,vo是视图层(表现层)的对象,pojo是自定义的类似于po或vo的综合体的简单Java bean.
package po;
//User的扩展类
public class UserCustom extends User {
}
package po;
import java.util.List;
public class UserQueryVo {
//基于用户的查询条件
private UserCustom userCustom;
public UserCustom getUserCustom() {
return userCustom;
}
public void setUserCustom(UserCustom userCustom) {
this.userCustom = userCustom;
}
//可以包装其它的查询条件,订单、商品
//...
}
3.在UserMapper.xml中定义用户信息综合查询(查询条件复杂,通过高级查询进行复杂关联查询)
<select id="findUserList" parameterType="UserQueryVo" resultType="UserCustom">
select * from user where sex= #{userCustom.sex} and username like ‘%${userCustom.username}%‘
</select>
4.定义Usermapper.java接口
public List<UserCustom> findUserList(UserQueryVo userQueryVo) throws Exception;
5.编写测试文件,测试成功。
@Test
public void testFindUserList() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
UserQueryVo userQueryVo = new UserQueryVo();
UserCustom userCustom = new UserCustom();
userCustom.setSex("1");
userCustom.setUsername("小明");
userQueryVo.setUserCustom(userCustom);
List<UserCustom> list = userMapper.findUserList(userQueryVo);
System.out.println(list);
}
6.传递hashmap
Sql映射文件定义如下:
<select id="findUserByHashmap" parameterType="hashmap" resultType="user">
select * from user where id=#{id} and username like ‘%${username}%‘
</select>
上边加粗标注的是hashmap的key。
测试:
Public void testFindUserByHashmap()throws Exception{
SqlSession session = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("id", 1);
map.put("username", "管理员");
List<User>list = userMapper.findUserByHashmap(map);
session.close();
}