今天遇到了两个问题,记录一下:
1.在实现类中调用Mapper接口查询sql,报空指针异常:
原因是Mapper接口上忘了加注解@Autowired
@Autowired
private UserMapper userMapper;
2.记录一下<foreach>的用法:
传入一串id的list(有可能有重复值),返回一个对象list,要求传入多少条就要查出多少条,不能去重;
@Override
public List<User> test(){
List<String> ids = new ArrayList<>();
ids.add("1");
ids.add("1");
ids.add("2");
List<User> users = userMapper.test(ids);
return users;
}
<!--返回三条-->
<select id="test" parameterType="java.util.List" resultType="User">
<foreach collection="list" item="id" separator="union all">
select * from user where id =#{id}
</foreach>
</select>
<!--返回两条-->
<select id="test" parameterType="java.util.List" resultType="User">
select * from user where id in
<foreach collection="list" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</select>
传入的list包含三个id,需要返回三条数据,separator定义的分隔符是union all,即用union all连接每个查询。
PS:以下是测试过程
<select id="test" parameterType="java.util.List" resultType="User">
<foreach collection="list" item="id">
select * from user where id =#{id}
</foreach>
</select>
直接这样写会报错,于是有了下面的写法:
<select id="test" parameterType="java.util.List" resultType="User">
<foreach collection="list" item="id" separator="union all">
select * from user where id =#{id} union all
</foreach>
select * from user where 1=2
</select>
这样写是可以正常运行的,最后的select * from user where 1=2永远不会查到数据,但是可以保证不报错。(union all前后查询字段要一致,union也会去重)
于是有了上边优化之后的写法。