Mybatis可以根据数据库的表自动生成实体类,Mapper接口,和Mapper.xml文件
需要用到的工具如下:
准备的jar包,两个jar包下载路径:mybatis-generator-core-1.3.2 myatis-3.3.0.jar
1.首先创建一个数据库表
DROP TABLE IF EXISTS `tb_device_inf`;
CREATE TABLE `tb_device_inf` (
`device_id` int(11) NOT NULL AUTO_INCREMENT,
`scan_time` varchar(50) NOT NULL,
`device_ip` varchar(20) NOT NULL,
`mac_address` varchar(30) DEFAULT NULL,
`os_detail` varchar(255) DEFAULT NULL,
`mac_vendor` varchar(255) DEFAULT NULL,
`device_type` varchar(255) DEFAULT NULL,
`port_detail` varchar(255) DEFAULT NULL,
`is_camera` int(2) DEFAULT NULL,
`area_code` varchar(20) DEFAULT NULL,
`ipc_detail` varchar(255) DEFAULT NULL,
PRIMARY KEY (`device_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.编写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>
<!-- 数据库驱动-->
<classPathEntry location="mysql-connector-java-5.1.35-bin.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost/<span style="color:#ff0000;">db_zjpsd</span>" userId="root" password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="com.xservice.h3c.pojo" targetProject="src">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="com.xservice.h3c.mapper" targetProject="src">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.xservice.h3c.dao" targetProject="src">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成哪些表-->
<table tableName="tb_device_inf" domainObjectName="Device" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
下面是文件生成的路径包名和连接数据库的URL,红色字体为数据库名
targetPackage="com.xservice.h3c.mapper" targetProject="src" <pre name="code" class="html"><pre name="code" class="html">connectionURL="jdbc:mysql://localhost/<span style="color:#ff0000;">db_zjpsd</span>" userId="root" password="root"
进入控制台窗口,在当前目录下,执行:Java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite
生成的文件的目录情况