SpringBoot中mybatis自动和注解返回类型HASHMAP转换驼峰标识方法
在mapper.xml中查询语句添加resultMap,resultMap的property对应实体类的set方法,colomn对应数据库字段。很多时候我们需要返回多表连接的值,没必要为了几个值新建一个实体类,一般用HashMap来做返回类型,而HashMap不自动返回驼峰标识怎么办?在Springboot中,可以通过设置map-underscore-to-camel-case属性为true来开启
前言:mybatis默认是属性名和数据库字段名一一对应的,即
数据库表列:user_name
实体类属性:user_name
但是java中一般使用驼峰命名
数据库表列:user_name
实体类属性:userName
很多时候我们需要返回多表连接的值,没必要为了几个值新建一个实体类,一般用HashMap来做返回类型,而HashMap不自动返回驼峰标识怎么办?
————————————————
方法一:添加yml配置
在Springboot中,可以通过设置map-underscore-to-camel-case属性为true来开启驼峰功能。
application.yml中:
mybatis:
configuration:
map-underscore-to-camel-case: true
application.properties中:
mybatis.configuration.map-underscore-to-camel-case:=true
注意如果返回类型是HashMap会使驼峰标识失效
方法二:运用Result功能
在mapper.xml中查询语句添加resultMap,resultMap的property对应实体类的set方法,colomn对应数据库字段。
<resultMap type="com.hui.readwrite.po.Count" id="CountMap">
<result property="id" column="id" jdbcType="INTEGER"/>
<result property="num" column="num" jdbcType="INTEGER"/>
<result property="name" column="name" jdbcType="VARCHAR"/>
<result property="address" column="address" jdbcType="VARCHAR"/>
<result property="aBC" column="a_b_c" jdbcType="VARCHAR"/>
</resultMap>
<!--查询单个-->
<select id="queryById" resultMap="CountMap">
select
id, num, `name`, address, a_b_c
from `count`
where id = #{id}
</select>
以及
@Result(property = "aBC", column = "a_b_c")
@Select("select * from count where id =#{id}")
Count selectById(Integer id);
如果对应多个字段
@Results(
@Result(property = "aBC", column = "a_b_c"),
@Result(property = "aXX", column = "a_x_x")
)
用注解来让HashMap转驼峰
如果是注解sql语句
@Result(property = "aBC", column = "a_b_c")@Select("select * from count where id =#{id}")HashMap selectById(Integer id);
如果是mapper.xml
<resultMap type="HashMap" id="HashMap">
<result property="aBC" column="a_b_c" jdbcType="VARCHAR"/>
</resultMap>
<!--查询单个-->
<select id="queryByIdHashMap" resultMap="HashMap">
select
id, num, `name`, address, a_b_c
from `count`
where id = #{id}
</select>
```

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)