使用MybatisGenerator自动生成Model,Mapping和Mapper文件

时间:2023-03-08 19:06:24

Mybatis和Hibernate都是持久层框架,MyBatis出现的比Hibernate晚,这两种框架我都用过,对于二者的优势我的感触不深,个人感觉MyBatis自动生成model,Mapping,mapper文件的功能使编码量减少,但也很容易出错,出错后还不易排查。

我在网上搜索了一下关于Mybatis和Hibernate的比较,知乎上的这个帖子讲得比较详细,大家可以参考一下

https://www.zhihu.com/question/21104468

想要自动生成文件,首先要下载MyBatis Generator Release,下载地址https://github.com/mybatis/generator/releases

生成的文件可以直接放在工程下面的正确的包目录下,但个人建议还是先新建一个文件夹,生成后再把对应的文件拷进不同的包路径下。

我使用的是Mysql数据库,这里还要下载一个用于连接数据库的jar包,官方网址:http://www.mysql.com/products/connector/

这里关键是配置generatorConfig.xml配置文件,我在src/main/resources目录下新建了generatorConfig.xml,代码如下

generatorConfig.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration>
<!-- 用于数据库连接的jar包 -->
<classPathEntry
location="D:/code/myeclipse/mybatisGenerator/mysql-connector-java-5.1.40-bin.jar"/>
<context id="my" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="false"/>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- 数据库连接配置 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost/book" userId="root"
password="zlj@123"/> <javaModelGenerator targetPackage="com.ese.book.pojo"
targetProject="D:/code/myeclipse/mybatisGenerator/model">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator> <sqlMapGenerator targetPackage="com.ese.book.mapping"
targetProject="D:/code/myeclipse/mybatisGenerator/mapping">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator> <javaClientGenerator targetPackage="com.ese.book.dao"
targetProject="D:/code/myeclipse/mybatisGenerator/dao" type="XMLMAPPER">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<table tableName="books" domainObjectName="Book"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
</table> </context>
</generatorConfiguration>

并把这个文件拷贝到和上面两个jar包同一路径下。文件夹内容为:

使用MybatisGenerator自动生成Model,Mapping和Mapper文件

条件准备好后,便可以生成文件了。生成语句:

java -jar mybatis-generator-core-1.3.5.jar -configfile generatorConfig.xml -overwrite

注:这个语句要在目标文件夹路径下执行,先要通过命令行进入D:\code\myeclipse\mybatisGenerator文件夹下。

使用MybatisGenerator自动生成Model,Mapping和Mapper文件

执行后dao,mapping,model文件夹下就会分别出现BookMapper.java,BookMapping.xml和Book.java文件。具体这里不在给出。