mybatis generato 生成的mapper映射xml出现重复代码
最近学习了mybaties ,学习了使用mybatis generator自动生成映射mapper.xml文件, 使用流程是首先创建maven项目, 在resources生成 mybatis-generator-config.xml配置文件 内容如下:
<?xml version="1.0" encoding="UTF-8"?> <!-- 4targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="com.test.po"
targetProject="src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 5targetProject:mapper映射文件生成的位置
如果maven工程只是单独的一个工程,targetProject="src/main/java"
若果maven工程是分模块的工程,targetProject="所属模块的名称",例如:
targetProject="ecps-manager-mapper",下同-->
<sqlMapGenerator targetPackage="com.test.dao"
targetProject="src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 6targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.test.dao"
targetProject="src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 7指定数据库表 -->
<table tableName="book_info"
enableCountByExample="false"
enableDeleteByExample="false"
enableSelectByExample="true"
enableUpdateByExample="false"
>
<property name="modelOnly" value="false" />
</table>
<table
tableName="book_type"
enableCountByExample="false"
enableDeleteByExample="false"
enableSelectByExample="true"
enableUpdateByExample="false"
<property name="modelOnly" value="false" />
</table>
<!--example:https://blog.csdn.net/sinat_30474567/article/details/72625651-->
</context>
然后在pom.xml配置对应的插件和需要的依赖包dependency
然后需要在上面的配置文件改一下内容,
最后点击edit configurations 添加mavenn命令mybatis-generator:generate -e,
执行一下,对应数据库里的实体类以及mapper接口以及映射xml就会自动生成了。
在生成完后发现出了一些问题,执行单元测试时报错 org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.neu.dao.EmpMapper.BaseResultMap
去对应的xml映射文件去看了一下,原来是生成映射文件xml生成了两次代码,resultmap生成了两次,很多方法也生成了两次,当然对于这个问题最直接的解决办法就是删除重复的,可是一但实体类比较多就删除比较麻烦了。
我去网上找了很多解决办法,导致的原因好像是mysql并不是完全支持这种创建模式,因此mgb(mybatis generator)创建有可能从其他数据库中找到与你表名相同的也会进行创建,因此就会出现 创建重复,解决办法有很多种
1.
在mgb配置文件的指定数据库表的地方加上schema="数据库名"对表加以区分,这样就可以解决了,但是mysql 8是不支持schema的,使用mysql8.0.11的我就要另行想办法了
2.
在mgb配置文件中把该部分注释掉就可以了,这样就是默认添加注释,然后测试了一下,确实没有再生成重复的resultmap和重复方法。这个解决办法的原理也不懂,但是确实测试过有效
3.mysql 8 对于第一种解决方法无法使用,但是官方给出了解决办法,jdbc连接新增nullCatalogMeansCurrent属性:
mysql 8 可以通过添加这个属性解决这种问题,代码就按照上面图中的示例就可以了
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=utf-8"
userId="root" password="root">
<property name="nullCatalogMeansCurrent" value="true" />
</jdbcConnection>
官方解释:
http://www.mybatis.org/generator/usage/mysql.html
上一篇: 堆溢出处理