List All elements are null, elementsnull
If ArrayList allows null values, java. lang. NullPointerException may occur during object conversion in the list.
Scenario:
Database select min (id) as id, min (name) as name from user where 1 = 2;
The queried records are not null, but null, resulting in the User object being null.
List <User> users = useDao. find (xxx); // size = 1, All elements are null
In this case, an error will be reported during operations on the user object!
Solution
Method 1: Remove null Elements
Example:
List <User> users = new ArrayList <User> (); users. add (null); users. add (null); users. add (null); System. out. println ("size:" + users. size (); // size: 3 for (User user: users) {try {System. out. println ("id:" + user. getId () + ", name:" + user. getName ();} catch (Exception ex) {System. out. println (ex); // java. lang. nullPointerException} users. remove (null); // remove the first null System. out. println ("size:" + users. size (); // size: 2 users. removeAll (Collections. singleton (null); // remove all null elements System. out. println ("size:" + users. size (); // size: 0 // does not enter the loop for (User user User: users) {try {System. out. println ("id:" + user. getId () + ", name:" + user. getName ();} catch (Exception ex) {System. out. println (ex );}}
Method 2: Ensure that no null value is found in the database, that is, if the null value is converted to the default value
Mysql can be implemented using ifnull/case when
Select ifnull (min (id),-1) as id, ifnull (min (name), 'defaultname') as name from user where 1 = 2;
Select case when min (id) is null then-1 else min (id) end as id, case when min (name) is null then 'defaultname' else min (name) end as name from user where 1 = 2;
The query result is as follows:
Id name
-1 defaultName
Summary: The specific situation is implemented based on the business. When you use clustering functions without the group by keyword in database query statistics, you must pay attention to the null value (group by is used for grouping statistics, if no record is found, there is no record.) If you want to always query a record and the element has a default value, do not display the record, depending on the business. Two scenarios correspond to two solutions.