mybatis generator生成代码工具的使用, 附demo
使用Hibernate时, 可以很方便的生成model,dao,和映射配置文件.在mybatis里, 也有生成器, 即mybatis generator, 简称MBG. 下面为大家介绍一下MBG的使用.
? ? 下载mybatis-generator-core-1.3.1-bundle.zip之后, 解压得到mybatis-generator-core-1.3.1.jar, 即生成器的jar包, 将mybatis-3.0.6.jar和mybatis-generator-core-1.3.1.jar加入到项目的lib里, 然后编写一个生成器的配置文件generatorConfig.xml.?
? ? 介绍一下genernatorConfig.xml
? ??<?xml version="1.0" encoding="UTF-8"?>
?其中的properties元素里引用了一个generatorConfig.properties配置文件是为了方便移植的时候,只需修改resource的路径值和generatorConfig.properties里的值即进行生成操作.
generatorConfig.properties代码如下:
?schema即为数据库名, tableName为对应的数据库表, domainObjectName是要生成的实体类, 如果想要mapper配置文件加入sql的where条件查询, 可以将enableCountByExample等设为true, 这样就会生成一个对应domainObjectName的Example类, enableCountByExample等设为false时, 就不会生成对应的Example类了.
配置文件配好了之后,
进行生成代码, 既可以使用命令的方式, 也可以自已写一个带main的类来运行, 下面提供了一个带main的运行类
MyBatisGeneratorTool.java
package com.yuan.mybatis.mbg.util;import java.io.File;import java.io.IOException;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import org.mybatis.generator.api.MyBatisGenerator;import org.mybatis.generator.config.Configuration;import org.mybatis.generator.config.xml.ConfigurationParser;import org.mybatis.generator.exception.InvalidConfigurationException;import org.mybatis.generator.exception.XMLParserException;import org.mybatis.generator.internal.DefaultShellCallback;public class MyBatisGeneratorTool {public static void main(String[] args) {List<String> warnings = new ArrayList<String>();boolean overwrite = true;String genCfg = "/generatorConfig.xml"; //src的一级目录下File configFile = new File(MyBatisGeneratorTool.class.getResource(genCfg).getFile());ConfigurationParser cp = new ConfigurationParser(warnings);Configuration config = null;try {config = cp.parseConfiguration(configFile);} catch (IOException e) {e.printStackTrace();} catch (XMLParserException e) {e.printStackTrace();}DefaultShellCallback callback = new DefaultShellCallback(overwrite);MyBatisGenerator myBatisGenerator = null;try {myBatisGenerator = new MyBatisGenerator(config, callback, warnings);} catch (InvalidConfigurationException e) {e.printStackTrace();}try {myBatisGenerator.generate(null);} catch (SQLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}}}?运行此类即可生成对应于数据库表的实体类, Mapper配置文件, Mapper接口, 生成后可以测试其可用性.
?
附件里是Demo
1 楼 naily 2012-02-24 不错 挺详细的
其实现在都用注解,补需要生成这么些东东的