Issue
I use mybatis to get data from MySql, I wanna know what will return when no data hitted, eg. the mapper method return List data type, when no data hitted by query condition, it will return empty list or null?
Solution
It's better to have an empty collection instead of null as a result of your query. When working with a collection you usually loop through each item and do something with it, something like this:
List<User> resultList = (List<User>) sqlSession.select("statementId");
for (User u : resultList) {
//...
}
which doesn't do anything if the list is empty.
But if you return null, you have to guard your code against NullPointerExceptions and write code like this instead:
List<User> resultList = (List<User>) sqlSession.select("statementId");
if (resultList != null) {
for (User u : resultList) {
//...
}
}
The first approach is usually better and MyBatis does it like that returning an empty list when no data is hitted, but you could force it to return null if that is really what you want.
Answered By - SARATHI
Answer Checked By - David Goodson (JavaFixing Volunteer)