还在使用mybatis的xml逐个映射字段?来看看mybatis返回Map(三种使用方式)
还在使用mybatis的xml逐个映射字段?来看看mybatis返回Map(三种使用方式)
SpringBoot+Mybatis返回Map(多种类型的map)
缘起
Mybatis自动映射了Java对象,属性–>数据库的表、字段,是一个半成品ORM(对象关系映射)框架,但是也会有一些业务场景,比如:多表联查,而过多的字段要在xml文件里面一一手动做映射,非常麻烦,那么我们可以直接在mybatis中返回一个map对象,字段什么的全都不用去手动定义(偷懒的一种方式_)。
也可以返回不同类型的Map,种类先贴出来,后面解释
-
List<Map<String, String>>
-
Map<String, <Map<String, String>>
-
Map<String, ProductEntity>
实现
用的技术:SpringBoot + mybatis plus + druid
mybatis plus是mybatis 的增强版,可以快速通过Java代码构建sql语句,极大节省了开发效率,但是遇到多表联查之类的业务场景,还是要老老实实使用mybatis的xml文件构建sql语句。
<properties>
<java.version>1.8</java.version>
<commons-codec.version>1.10</commons-codec.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<fast.version>1.2.78</fast.version>
<mybatis-plus>3.4.1</mybatis-plus>
<druid.version>1.1.14</druid.version>
</properties>
List<Map<String, String>>
xml文件
<select id="listProduct" resultType="map">
select * from product
</select>
Mapper文件
public interface ProductMapper extends BaseMapper<ProductEntity> {
List<Map<String, Object>> listProduct();
}
启动调用后报错
Error attempting to get column 'created' from result set. Cause: java.sql.SQLFeatureNotSupportedException\n; null; nested exception is java.sql.SQLFeatureNotSupportedException
是druid的版本太低了,调整一下版本,1.1.21
及以上即可
<druid.version>1.1.21</druid.version>
看调试结果
解读:
list中每个map对象,对应着表中的一条记录。
Map<String, <Map<String, String>>
xml文件
<select id="listProduct" resultType="map">
select * from product
</select>
Mapper文件
// 以 id列为key, 对应的一条记录为value
@MapKey("id")
Map<String, Map<String, Object>> listProduct();
调试
解读:
外层map中以返回的id为key,整条记录作为value存入。内层map中key是每条记录中的字段名称,value是对应字段的值。
Map<String, ProductEntity>
xml文件
<select id="listProduct" resultType="com.zlhy.calculation.entity.mybatis.ProductEntity">
select * from product
</select>
Mapper文件
@MapKey("id")
Map<String, ProductEntity> listProduct();
调试
解读:
以返回的id作为key,整条记录作为实体类对象返回到Map中。
温馨提示:
以上返回map尽量用于不需要对map中返回的数据进行数据操作,否则用起来还是不太方便的(字段名也都是写死的,如果后续数据库中表字段要进行修改,那么改动起来有点麻烦),而如果涉及到单表查询或多表连查时如果对mapper返回的数据操作力度较小,可以使用返回map的方式。
更多推荐
所有评论(0)