A return data type generally
For example, to obtain a field value in the database based on the id attribute.
mapper interfaces:
// 根据 id 获得数据库中的 username 字段的值
String getEmpNameById(Integer id);
SQL mapping file:
<!--
指定 resultType 返回值类型时 String 类型的,
string 在这里是一个别名,代表的是 java.lang.String
对于引用数据类型,都是将大写字母转小写,比如 HashMap 对应的别名是 'hashmap'
基本数据类型考虑到重复的问题,会在其前面加上 '_',比如 byte 对应的别名是 '_byte'
-->
<select id="getEmpNameById" resultType="string">
select username from t_employee where id = #{id}
</select>
Second, the return type JavaBean
Such as access to information in the database according to a field, the package information query result into a JavaBean type of data.
mapper interfaces:
// 根据 id 查询信息,并把信息封装成 Employee 对象
Employee getEmpById(Integer id);
SQL mapping file:
<!--
通过 resultType 指定查询的结果是 Employee 类型的数据
只需要指定 resultType 的类型,MyBatis 会自动将查询的结果映射成 JavaBean 中的属性
-->
<select id="getEmpById" resultType="employee">
select * from t_employee where id = #{id}
</select>
Third, the return List
type
Sometimes the data we want to query more than one, such as: Fuzzy query, full-table query, this time may be more than the returned data is a data for processing multiple data can be stored in List
the collection.
mapper interfaces:
// 假如是全表查询数据,将查询的数据封装成 Employee 类型的集合
List<Employee> getAllEmps();
SQL mapping file:
<!--
注意这里的 resultType 返回值类型是集合内存储数据的类型,不是 'list'
-->
<select id="getAllEmps" resultType="employee">
select * from t_employee
</select>
Fourth, the return Map
type
MyBatis also supports data package into a query Map
.
1. If the result of the query is one, we can query data in a {表字段名, 对应的值}
manner to deposit Map
in.
mapper interfaces:
// 根据 id 查询信息,并把结果信息封装成 Map
Map<String, Object> getEmpAsMapById(Integer id);
SQL mapping file:
<!--
注意这里的 resultType 返回值类型是 'map'
-->
<select id="getEmpAsMapById" resultType="map">
select * from t_employee where id = #{id}
</select>
Below the results of data queries posted for your reference:
2. If the result of the query is a plurality of data, we can also query data in a {表中某一字段名, JavaBean}
way to package into Map
.
mapper interfaces:
// 查询所有员工的信息,把数据库中的 'id' 字段作为 key,对应的 value 封装成 Employee 对象
// @MapKey 中的值表示用数据库中的哪个字段名作 key
@MapKey("id")
Map<Integer, Employee> getAllEmpsAsMap();
SQL mapping file:
<!--
注意 resultType 返回值类型,不再是 'map',而是 Map 的 value 对应的 JavaBean 类型
-->
<select id="getAllEmpsAsMap" resultType="employee">
select * from t_employee
</select>
Here is the result of a query (only interception part):
MyBatis allows the results of the query into a package Map
, such a mechanism is excellent.
Fifth, expand
Extension. Returns the result of the above forms are based on the query ( select
), in fact, change operations for additions and deletions may also return a certain type of data, for example Boolean
, Integer
and the like.