欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

SpringBoot配置mybatis驼峰命名规则自动转换的实现

时间:2021-03-30 09:08:13|栏目:JAVA代码|点击:

一、简述

mybatis驼峰式命名规则自动转换:

  • 使用前提:数据库表设计按照规范“字段名中各单词使用下划线"_"划分”;
  • 使用好处:省去mapper.xml文件中繁琐编写表字段列表与表实体类属性的映射关系,即resultMap。

示例:

 <resultMap id ="UserInfoMap" type="com.example.mybaitsxml.dao.entity.User">
  <result column="name_" property="name"/>
  <result column="sex" property="sex"/>
  <result column="age" property="age"/>
  <result column="class_no" property="classNo"/>
 </resultMap>

SpringBoot整合mybatis,开启mybatis驼峰式命名规则自动转换,通常根据配置文件不同分为两种方式。

1、方式一

直接application.yml文件中配置开启

#mybatis配置
mybatis:
 typeAliasesPackage: com.example.mybaitsxml.dao.entity
 mapperLocations: classpath:mapper/*.xml
 configuration:
 map-underscore-to-camel-case: true

2、方式二

mybatis-config.xml文件中配置开启,application.yml文件指定配置文件。

application.yml文件:

#mybatis配置
mybatis:
 typeAliasesPackage: com.example.mybaitsxml.dao.entity
 mapperLocations: classpath:mapper/*.xml
 configLocation: classpath:/mybatis-config.xml

mybatis-config.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
 <!--开启驼峰命名规则自动转换-->
 <settings>
 <setting name="mapUnderscoreToCamelCase" value="true" />
 </settings>
</configuration>

注:关于xml文件,如果删除或者注释掉所有内容,会报错:"Valid XML document must hava a root tag",若忽略这个报错直接运行,程序报错:

“Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 11; columnNumber: 24; 文件提前结束。”

3、小结

开启mybatis驼峰式命名规则转换可以省去xml文件中resultMap编写的麻烦,只需要为resultType指定数据库表对应的实体类即可,但是考虑程序的安全性以及映射灵活性,通常开发中还是将resultMap结合使用。

上一篇:java版微信公众平台后台接入

栏    目:JAVA代码

下一篇:idea企业开发之新建各类型项目的详细教程

本文标题:SpringBoot配置mybatis驼峰命名规则自动转换的实现

本文地址:http://www.codeinn.net/misctech/91073.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有