当前位置:网站首页>Record: call mapper to report null pointer Foreach > the usage of not removing repetition;

Record: call mapper to report null pointer Foreach > the usage of not removing repetition;

2022-04-23 20:06:00 qq_ forty-three million four hundred and thirty-two thousand an

I have two problems today , Make a note of :
1. Call in implementation class Mapper Interface query sql, The null pointer is abnormal :
as a result of Mapper Forgot to annotate the interface @Autowired

@Autowired
private UserMapper userMapper;

2. Make a note of <foreach> Usage of :
A string of id Of list( There may be duplicate values ), Return an object list, Find out as many as you want , You can't get rid of it ;

@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;
 }
<!-- Return to three -->
<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>

<!-- Return two -->
<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>

Incoming list Contains three id, Three pieces of data need to be returned ,separator The delimiter defined is union all, The box union all Connect each query .

PS: The following is the test process

<select id="test" parameterType="java.util.List" resultType="User">
	<foreach collection="list" item="id">
		select * from user where id =#{id}
	</foreach>
</select>

Writing this directly will report an error , So here's how to write it :

<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>

It can work normally , final select * from user where 1=2 Never find the data , But you can guarantee that no error will be reported .(union all The fields before and after the query should be consistent ,union Will also go heavy )
So there is the writing method after the above optimization .

版权声明
本文为[qq_ forty-three million four hundred and thirty-two thousand an]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231946348773.html