MyIbatis学习 (一)--使用Generator自动生成代码

来源:互联网 发布:仓库管理系统java 编辑:程序博客网 时间:2024/06/06 14:01

Myibatis-Generator调用方式

Eclipse集成generator插件(常用)

1、在线安装generator插件

打开eclipse,点击Help>Software Update

选择 "Available Software" 标签,点击 "Add Site" 按钮

输入以下信息:

Location:http://mybatis.googlecode.com/svn/sub-projects/generator/trunk/eclipse/UpdateSite/

点击ok,自动进入 "mybatis generator Feature"

点击“install”按钮进行安装。。。。mybatis generator 插件安装完成

2、离线安装generator插件

参看:http://jingyan.baidu.com/article/9faa7231506ed8473c28cbee.html

3、generator调用

generator插件安装好之后,然后编写生成配置文件generatorConfig.xml,eclipse中在这个文件上右键,就有Generate Mybatis/iBatis Artifacts,由此就可以生成代码了。generatorConfig.xml文件详细内容之后有示例,这里先不贴出来,使用eclipse插件的方式有个不同就是targetProject的配置是项目名开头的,比如其他配置是targetProject="src/main/java",在这里就要是targetProject="项目名/src/main/java"。这里为什么要加上项目名,可能是因为eclipse插件是针对ide的,需要指定ide内是哪个项目。

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="D:/ojdbc5-11.2.0.2.0.jar" />    <context id="context1" >  <!-- 配置连接数据信息 -->      <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@192.168.1.233:1521:orcl" userId="cmss" password="cmss" />      <!-- 配置自动生成的Model的保存路径与其它参数 -->  <javaModelGenerator targetPackage="com.entity.main" targetProject="MyIbatisGeneratorForPage\src\main\java" /> <!-- 配置自动生成的Mappper.xml映射的保存路径与其它参数 -->  <sqlMapGenerator targetPackage="config.myibatis.xml" targetProject="MyIbatisGeneratorForPage\src\main\resources" /><!-- 配置自动生成的Mappper.java接口的保存路径与其它参数 -->  <javaClientGenerator targetPackage="com.dao" targetProject="MyIbatisGeneratorForPage\src\main\java" type="XMLMAPPER" />  <!--    <table schema="" tableName="T_SYS_USER"></table>    <table schema="" tableName="T_SYS_ROLE"></table>    <table schema="" tableName="T_SYS_ORG"></table>    <table schema="" tableName="T_SYS_ROLE_RES"></table>    <table schema="" tableName="T_SYS_RESOURCE"></table>    <table schema="" tableName="T_SYS_USER_ROLE"></table>     -->     <!-- 生成表对应的操作与实体对象 -->       <table schema="" tableName="T_CORE_ORG_HIS"></table>  </context></generatorConfiguration>



Maven中集成Myibatis-Generator插件(常用)

自动生成代码步骤:

1.创建一个Maven项目:File——New Project——Maven

2.在pom文件中,添加Myibatis-Generator插件,IDE会自动帮我们下载插件

(如果没反应,可以点开右侧Maven Project选项卡刷新以下)

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>Mybatis_Generator</groupId>    <artifactId>Mybatis_Generator</artifactId>    <version>1.0-SNAPSHOT</version>    <build>        <finalName>mybatis_generator</finalName>        <plugins>            <plugin>                <groupId>org.mybatis.generator</groupId>                <artifactId>mybatis-generator-maven-plugin</artifactId>                <version>1.3.0</version>            </plugin>        </plugins>    </build></project>

3.在src/main/resource目录下创建generatorConfig.xml文件

(官方配置以及说明:http://go.rritw.com/mybatis.github.io/generator/configreference/xmlconfig.html)

<?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="E:\mysql-connector-java-5.1.7-bin.jar" />    <context id="DB2Tables" targetRuntime="Ibatis2Java5">        <!--去除注释 (true好像不起作用) -->        <commentGenerator>            <property name="suppressAllComments" value="true" />        </commentGenerator>        <!--数据库连接 -->        <jdbcConnection driverClass="com.mysql.jdbc.Driver"                        connectionURL="jdbc:mysql://localhost:3306/news"                        userId="root"                        password="">        </jdbcConnection>        <!--默认false           Java type resolver will always use java.math.BigDecimal if the database column is of type DECIMAL or NUMERIC.         -->        <javaTypeResolver >            <property name="forceBigDecimals" value="false" />        </javaTypeResolver>        <!--生成实体类 指定包名 以及生成的地址 (可以自定义地址,但是路径不存在不会自动创建  使用Maven生成在target目录下,会自动创建) -->        <javaModelGenerator targetPackage="com.qianyan.model" targetProject="MAVEN">            <property name="enableSubPackages" value="false" />            <property name="trimStrings" value="true" />        </javaModelGenerator>        <!--生成SQLMAP文件 -->        <sqlMapGenerator targetPackage="com.qianyan.persistence.ibatis"  targetProject="MAVEN">            <property name="enableSubPackages" value="false" />        </sqlMapGenerator>        <!--生成Dao文件 可以配置 type="XMLMAPPER"生成xml的dao实现  context id="DB2Tables" targetRuntime="MyBatis3"  -->        <javaClientGenerator type="SPRING" targetPackage="com.qianyan.persistence.dao"  targetProject="MAVEN">            <property name="enableSubPackages" value="false" />        </javaClientGenerator>        <!--对应数据库表 mysql可以加入主键自增 字段命名 忽略某字段等-->        <table tableName="USER" domainObjectName="User" >        </table>    </context></generatorConfiguration>
4.点击Maven Project——项目——Plugins——mybatis generator——Run Maven build

5.可以根据自己项目的配置,把生成的代码拷贝到自己的项目中去


生成代码使用

mybatis设计比较巧妙,Dao层就不用说了,这里主要介绍下实体类User和UserExample

User类就是普通的实体类,定义了数据库对应的字段,以及set/get方法

Example类是干嘛的呢?用其它项目中的几个例子还说明一下吧

1.比如在一个项目 我们要删除某个小组下某个用户的信息

public int deleteUserApplyInfo(long user_id,long team_id){        StudyTeamUserApplyInfoExample ue = new StudyTeamUserApplyInfoExample();        ue.createCriteria()                .andUserIdEqualTo(new BigDecimal(user_id))                .andTeamIdEqualTo(new BigDecimal(team_id));        return studyTeamUserApplyInfoDAO.deleteByExample(ue);    }

2.根据小组ID(非主键 更新小组信息)
public int updateStudyTeamInfo(StudyTeamInfo st){        StudyTeamInfoExample ste = new StudyTeamInfoExample();        ste.createCriteria().andTeamIdEqualTo(st.getTeamId());        return studyTeamInfoDAO.updateByExampleSelective(st,ste);    }
3.(1)模糊查询并且排序 (2)大于等于某个分数 并且小于某个分数的查询
public List<StudyTeamInfo> getStudyTeamInfoByName(String team_name){        StudyTeamInfoExample se = new StudyTeamInfoExample();        se.createCriteria().andTeamNameLike("%"+team_name+"%").andEnableEqualTo((short)1);        se.setOrderByClause("team_score desc");        List<StudyTeamInfo> ls = studyTeamInfoDAO.selectByExample(se);        if(ls!=null&&ls.size()>0){            return ls;        }        return null;    }

Example中提供了Critertia,一种面向对象的查询方式,并且根据实体类中字段的属性,生成不同的操作。

当然你也可以根据实际需要直接使用实体类进行增删改查


3. 直接运行jar(不常用)

为了简单起见,我把jar文件跟生成配置文件拷贝到一起mybatis-generator-core-1.3.2.jar和generatorConfig.xml,这里的xml文件要加上jdbs驱动的路径,在<generatorConfiguration>内部加上
<classPathEntry location="C:\Users\Administrator\.m2\repository\mysql\mysql-connector-java\5.1.24\mysql-connector-java-5.1.24.jar"/>
java -jar mybatis-generator-core-1.3.2.jar -configfile F:/xy/generatorConfig.xml -overwrite 
这样也可正常生成。
这里有段使用生成代码的小例子,需要mybatis的配置文件MapperConfig.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>     <environments default="development">        <environment id="development">            <transactionManager type="JDBC"/>            <dataSource type="POOLED">                <property name="driver" value="com.mysql.jdbc.Driver" />                  <property name="url" value="jdbc:mysql://localhost/test" />                  <property name="username" value="test" />                  <property name="password" value="test" />             </dataSource>        </environment>    </environments>    <mappers>        <mapper resource="mapper/com/xxx/mybatis/UsersMapper.xml"/>    </mappers></configuration>


这里的mapper内的属性,netbeans会自动提示resources,应该是resource。坑爹的是,这里写s结尾的,报错却说mapper应该配置属性resources,然后删除s配置resource才不会报错。在下载的mybatis-generator-config_1_0.dtd文件可以看到正确的定义。然后java调用:
Reader reader = Resources.getResourceAsReader("config/MapperConfig.xml");        SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);        SqlSession sqlSession = sqlMapper.openSession();                UsersExample example = new UsersExample();        example.createCriteria().andPasswordIsNotNull();        try {            UsersMapper mapper = sqlSession.getMapper(UsersMapper.class);            List<Users> users = mapper.selectByExample(example);            for (Users u : users)                  System.out.println(u.getUsername() + " -- " + u.getPassword());         } finally {            sqlSession.close();        }


4. 自行编写代码(不常用)

官方有说明http://mybatis.org/generator/running/runningWithJava.html
直接上代码
...
import org.mybatis.generator.api.MyBatisGenerator;import org.mybatis.generator.config.Configuration;import org.mybatis.generator.config.xml.ConfigurationParser;import org.mybatis.generator.internal.DefaultShellCallback;...        List<String> warnings = new ArrayList<String>();        final boolean overwrite = true;        File configFile = new File("src/main/resources/config/generatorConfig.xml");        //System.out.println("config fiel is in : " + configFile.getAbsoluteFile());        ConfigurationParser cp = new ConfigurationParser(warnings);        Configuration configuration = cp.parseConfiguration(configFile);        DefaultShellCallback callback = new DefaultShellCallback(overwrite);        MyBatisGenerator mybatisGenerator = new MyBatisGenerator(configuration, callback, warnings);        mybatisGenerator.generate(null);

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><!-- 引入配置文件 --><properties resource="init.properties"/><!-- 指定数据连接驱动jar地址 --><classPathEntry location="${classPath}" /><!-- 一个数据库一个context --><context id="infoGuardian"><!-- 注释 --><commentGenerator ><property name="suppressAllComments" value="false"/><!-- 是否取消注释 --><property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳--></commentGenerator><!-- jdbc连接 --><jdbcConnection driverClass="${jdbc_driver}"connectionURL="${jdbc_url}" userId="${jdbc_user}"password="${jdbc_password}" /><!-- 类型转换 --><!-- false:JDBC DECIMAL、NUMERIC类型解析为Integer,默认方式 -->    <!-- true: JDBC DECIMAL、NUMERIC类型解析为java.math.BigDecimal --><javaTypeResolver><!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) --><property name="forceBigDecimals" value="false"/></javaTypeResolver><!-- 生成实体类地址 --><javaModelGenerator targetPackage="com.oop.eksp.user.model"targetProject="${project}" ><!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --><property name="enableSubPackages" value="false"/><!-- 是否针对string类型的字段在set的时候进行trim调用 --><property name="trimStrings" value="true"/></javaModelGenerator><!-- 生成mapxml文件 --><sqlMapGenerator targetPackage="com.oop.eksp.user.data"targetProject="${project}" ><!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --><property name="enableSubPackages" value="false" /></sqlMapGenerator><!-- 生成mapxml对应client,也就是接口dao --><javaClientGenerator targetPackage="com.oop.eksp.user.data"targetProject="${project}" type="XMLMAPPER" ><!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --><property name="enableSubPackages" value="false" /></javaClientGenerator><!-- 配置表信息 --><table schema="${jdbc_user}" tableName="s_user"domainObjectName="UserEntity" enableCountByExample="false"enableDeleteByExample="false" enableSelectByExample="false"enableUpdateByExample="false"><!-- schema即为数据库名 tableName为对应的数据库表 domainObjectName是要生成的实体类 enable*ByExample 是否生成 example类   --><!-- 忽略列,不生成bean 字段 --><ignoreColumn column="FRED" /><!-- 指定列的java数据类型 -->      <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /></table></context></generatorConfiguration>



1、table标签解析
①属性
schema即为数据库名,tableName为对应的数据库表,domainObjectName是要生成的实体类。
若要生成例子可将enableCountByExample等设为true, 就会生成一个对应domainObjectName的Example类,false则不生成,默认策略是true。
类似的还有enableUpdateByExample、enableDeleteByExample、enableSelectByExample、selectByExampleQueryId属性。

②子标签
若要对某些数据库字段进行操作,可以在table标签中加入如下标签
1、忽略某个字段 
<ignoreColumn column="name" />
2、无论数据库字段是何类型,生成的类属性都是varchar
<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
2、总结
使用Mybatis Generator需要
①两个jar包——mybatis-generator-core-1.3.2.jar和数据库jar包
②一个配置文件generator.xml
③执行语句(java -jar F:\xy\jars\mybatis-generator-core-1.3.2.jar -configfile F:\xy\generator.xml -overwrite

3、注意事项
①generator.xml格式:必须是以UTF-8无BOM格式编码,用notepad++转换。
②注意数据库包的可用性,无效的数据库包转换会报错。

附带上我的init.properties
#Mybatis Generator configurationproject = EKSPclassPath=E:/workplace/EKSP/WebContent/WEB-INF/lib/ojdbc14.jarjdbc_driver = oracle.jdbc.driver.OracleDriverjdbc_url=jdbc:oracle:thin:@127.0.0.1:1521:orcljdbc_user=INFOGUARDIANjdbc_password=info_idap132






0 0