假设,我们将来的实体类中,或者数据库中的表字段过多。还有就是在关联查询中可以使用Map快速的返回想要的对象集合。我们应当考虑使用Map!
1.编写接口
public List<User> select(Map map);
2.编写对应mapper中的sql语句
<select id="select" resultType="com.dencycheng.entiy.User">
select * from user
where
1 = 1
<if test="userId != null">
and id = #{userId}
</if>
<if test="username != null">
and name like CONCAT('%',#{username},'%')
</if>
<if test="password != null">
and pwd = #{pwd}
</if>
</select>
3.测试
@Test
public void select() {
SqlSession sqlSession = null;
try {
//获取SqlSession
sqlSession = MybatisUtils.getSqlSession();
//获取mapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map paraMap = new HashMap<>();
paraMap.put("userId",1);
List<User> select = mapper.select(paraMap);
select.forEach(x->{
System.out.println(x);
});
} finally {
//关闭sqlSession
sqlSession.close();
}
}
4.测试结果
User{id=1, name='z', pwd='1'}
表结构
user表
-- auto-generated definition
create table user
(
id int(20) auto_increment
primary key,
name varchar(30) null,
pwd varchar(30) null
);
order表
-- auto-generated definition
create table `order`
(
id int auto_increment
primary key,
userId int null,
price decimal null,
name varchar(20) null
);
此处不介绍resultMap的用法。介绍个野路子
当我们需要关联查询的时候我们可以用Map作为返回结果。如果不用的话也可以使用resultMap的方式。
1.编写接口
public List<Map> userOrders(String username);
2.编写对应mapper中的sql语句
<select id="userOrders" resultType="map">
select `order`.*,user.name from `order` inner join user on `order`.userId = user.id
where user.name = #{name};
</select>
3.测试
@Test
public void userOrders() {
SqlSession sqlSession = null;
try {
//获取SqlSession
sqlSession = MybatisUtils.getSqlSession();
//获取mapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<Map> select = mapper.userOrders("黑猫");
select.forEach(x->{
System.out.println(x);
});
} finally {
//关闭sqlSession
sqlSession.close();
}
}
4.结果
{price=20, name=菊花茶, id=1, userId=2}