Most of the time, you know exactly the column names of a database table you are retrieving the data from. But there might be times when you just want to display the table dynamically without knowing the column names beforehand, for instance when you need to write an admin module.
If you use normal JDBC, you normally use the
ResultSetMetaData object to achieve that and you can get all the column names from there. But how are you gonna do it in
MyBatis? There are some other more complicated ways to do it but this is the simplest and the most straight forward.
The solution is to use
resultType instead of
resultMap in MyBatis mapping config as the following.
<select resultType="java.util.LinkedHashMap"
id="getTableData "
parameterType="String"
>
${queryString}
</select>
We use
java.util.LinkedHashMap for
resultType. You can also use normal
HashMap but you might not wanna use that because
HashMap doesn't maintain the insertion order. That's about it for the configuration. You do not need to configure the mapper for the
resultType like
resultMap because
MyBatis automatically populates the results in
LinkedHashMap for you.
So let's suppose, this is the MyBatis DAO interface.
public interface Xyz {
public List<Map> getTableData(Query query);
}
Note the return type. It must be a
List. MyBatis returns a list of
Map objects. One
Map object represents one row of data.
In a
Map object, the "
key" is column name and the value is the value of that column in the respective row.
This is it. Call the method and now you've got all the column names and values.
If you need column names, you can just call
keySet() from the
Map object and you will get all the column names in a
Set.
Just iterate through the
List, iterate through each
Map object inside, print it out and experiment with it. You will know what you have to do next.