mybatis使用方便,但是各种配置文件、bean及dao的重复书写很是烦人。幸好mybatis已经有了自动生成工具:常用的方式有命令行、maven、eclipse插件。下面,将介绍eclipse及maven的方式生成mybatis代码。
一、eclipse中使用插件生成代码
1.首先需要在eclipse中安装ibator插件
根据说明,在eclipse中安装ibator插件,然后重启eclipse。
2.验证ibator插件是否安装成功
在eclipse中依次点击:File–New–other,在搜索框中输入ib,如果出现如下所示,则说明安装成功。
3.新建java项目,在src下右键New–Other
点击Next,在File Name中输入ibatorConfig.xml,点击完成,就会在src下生存所需的配置文件。
4.ibatorConfig.xml配置
ibatorConfiguration PUBLIC "-//Apache Software Foundation//DTD Apache iBATIS Ibator Configuration 1.0//EN" "http://ibatis.apache.org/dtd/ibator-config_1_0.dtd" >
connectionURL="jdbc:mysql://localhost:3306/spring4mybatis"
userId="root" password="******" />
targetProject="IbatorDemo" />
targetProject="IbatorDemo" />
targetProject="IbatorDemo" implementationPackage="com.ibator.dao.impl"
type="IBATIS" />
5.配置完成后,在该文件上右击,选择Generate IBATIS Artifacts,然后在IbatorDemo项目下就会看到生成的代码。
注:当使用的daoGenerator类型为SPRING时,生成的dao所继承的类为SqlMapClientDaoSupport,但是在spring 3.2之后该方法已经废弃,所以如果所用spring版本在3.2之后,应该使用org.mybatis.spring.support.SqlSessionDaoSupport。
二、maven生成mybatis代码
1.新建maven项目
2.修改pom.xml文件
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
IbatorDemo
com.ibator
war
0.0.1-SNAPSHOT
IbatorDemo Maven Webapp
http://maven.apache.org
junit
junit
3.8.1
test
IbatorDemo
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.2
true
true
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.2
3.在src/main/resources下建立配置文件generatorConfig.xml
generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
password="******">
4.项目上右键–run as–maven build
点击run,完成。