Mybatis逆向工程构建项目实例.

时间:2023-03-09 00:31:33
Mybatis逆向工程构建项目实例.

2016/11/06更新: 
因为有博友可能需要这份代码, 所以我就直接发到百度云上面和大家共享, 如果链接失效请大家留言提示即可.
下载地址: http://pan.baidu.com/s/1i57E8PR

mybaits需要程序员自己编写sql语句,mybatis官方提供逆向工程 可以针对单表自动生成mybatis执行所需要的代码(mapper.java,mapper.xml、pojo等)
有了sql表的结构后, 我们就可以利用逆向工程直接生成相应的Dao和JavaBean代码, 这样能够大大减少我们平时开发的工作量.

但是我还是觉得使用逆向工程局限性很大, 例如我们的逆向工程main方法只能执行一次, 如果再次执行就会继续生成相应的Dao和JavaBean, 除非我们把之前生成的全都删除. 这样对于代码的扩展性就不是很好, 如果我们需要对表结构进行修改, 那么我们就必须对生成的Dao和JavaBean进行一个个修改.

下面就直接进入开发阶段:

1, 数据库表结构
Mybatis逆向工程构建项目实例.

2,将逆向工程导入到Eclipse中
Mybatis逆向工程构建项目实例.

3,使用逆向工程
逆向工程目录结构:
Mybatis逆向工程构建项目实例.

这里的bean和dao都是使用逆向工程自动生成的两个包, 我们只需要将相应的Dao和Javabean拷贝到相应的project下即可.
看下生成Dao和Bean的代码:

 import java.io.File;
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.internal.DefaultShellCallback; public class GeneratorSqlmap { public void generator() throws Exception{ List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
callback, warnings);
myBatisGenerator.generate(null); }
public static void main(String[] args) throws Exception {
try {
GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
generatorSqlmap.generator();
} catch (Exception e) {
e.printStackTrace();
} } }


下面就是看下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>
<context id="testTables" targetRuntime="MyBatis3"> <!-- JavaBean 实现 序列化 接口 -->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin">
</plugin>
<!-- genenat entity时,生成toString -->
<plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
<!-- 自定义物理分页 可生成支持Mysql数据的limit 不支持Oracle -->
<plugin type="org.mybatis.generator.plugins.page.PaginationPlugin" />
<!-- 自定义查询指定字段 -->
<plugin type="org.mybatis.generator.plugins.field.FieldsPlugin" />
<!-- 开启支持内存分页 可生成 支持内存分布的方法及参数
<plugin type="org.mybatis.generator.plugins.RowBoundsPlugin" />
-->
<!-- generate entity时,生成hashcode和equals方法
<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin" />
-->
<!-- 此处是将Example改名为Criteria 当然 想改成什么都行~ -->
<plugin type="org.mybatis.generator.plugins.RenameExampleClassPlugin">
<property name="searchString" value="Example$" />
<!-- 替换后
<property name="replaceString" value="Criteria" />
-->
<property name="replaceString" value="Query" />
</plugin>
<!-- 此处是将UserMapper.xml改名为UserDao.xml 当然 想改成什么都行~ -->
<plugin type="org.mybatis.generator.plugins.rename.RenameSqlMapperPlugin">
<property name="searchString" value="Mapper" />
<property name="replaceString" value="Dao" />
</plugin> <!-- 此处是将UserMapper改名为UserDao 接口 当然 想改成什么都行~ -->
<plugin type="org.mybatis.generator.plugins.rename.RenameJavaMapperPlugin">
<property name="searchString" value="Mapper$" />
<property name="replaceString" value="Dao" />
</plugin> <commentGenerator type="org.mybatis.generator.plugins.comment.MyCommentGenerator">
<!-- 是否去除自动生成的注释 true:是 : false:否
<property name="suppressAllComments" value="true" />
-->
</commentGenerator> <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/babasport" userId="root"
password="123456">
</jdbcConnection>
<!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg"
userId="yycg"
password="yycg">
</jdbcConnection> --> <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver> <!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="cn.itcast.core.bean"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator> <!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="cn.itcast.core.dao"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="cn.itcast.core.dao"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="true" />
</javaClientGenerator> <!-- 指定数据库表 -->
<!-- 用户模块表 -->
<table schema="" tableName="bbs_buyer" domainObjectName="user.Buyer"/> <!-- 商品模块表 -->
<table schema="" tableName="bbs_product" domainObjectName="product.Product">
<!-- 商品介绍 大字段映射 -->
<columnOverride column="description" javaType="String" jdbcType="VARCHAR" />
<!-- 包装清单 大字段映射 -->
<columnOverride column="package_list" javaType="String" jdbcType="VARCHAR" />
<!-- 商品图片 大字段映射 -->
<columnOverride column="img_url" javaType="String" jdbcType="VARCHAR" />
</table>
<table schema="" tableName="bbs_brand" domainObjectName="product.Brand"/>
<table schema="" tableName="bbs_Color" domainObjectName="product.Color"/>
<table schema="" tableName="bbs_sku" domainObjectName="product.Sku"/> <!-- 订单模块表 -->
<table schema="" tableName="bbs_order" domainObjectName="order.Order">
<!-- 支付方式 0:到付 1:在线 2:邮局 3:公司转帐 -->
<columnOverride column="payment_way" javaType="Integer"/>
<!-- 货到付款方式.1现金,2POS刷卡 -->
<columnOverride column="payment_cash" javaType="Integer" />
<!-- 送货时间 -->
<columnOverride column="delivery" javaType="Integer"/>
<!-- 支付状态 :0到付1待付款,2已付款,3待退款,4退款成功,5退款失败 -->
<columnOverride column="is_paiy" javaType="Integer"/>
<!-- 订单状态 0:提交订单 1:仓库配货 2:商品出库 3:等待收货 4:完成 5待退货 6已退货 -->
<columnOverride column="state" javaType="Integer"/>
<!-- 订单状态 默认Boolean -->
<columnOverride column="order_state" javaType="Integer"/>
</table>
<table schema="" tableName="bbs_detail" domainObjectName="order.Detail"/> <!-- 指定数据库所有表
<table schema="" tableName="%"/>
--> <!-- 有些表的字段需要指定java类型
<table schema="" tableName="">
<columnOverride column="" javaType="" />
</table> -->
</context>
</generatorConfiguration>

主要核心内容就是在这个配置文件中写入相应的配置, 具体的使用方法和配置注释中都有说明.

4, 使用逆向工程进行增删改查操作

 package cn.itcast;

 import java.util.Date;
import java.util.List; import javax.annotation.Resource; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import cn.itcast.core.bean.TestTb;
import cn.itcast.core.bean.product.Product;
import cn.itcast.core.bean.product.ProductQuery;
import cn.itcast.core.dao.TestTbDao;
import cn.itcast.core.dao.product.ProductDao;
import cn.itcast.core.service.TestTbService; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:application-context.xml"})
public class TestProduct { @Resource
private ProductDao productDao; @Test
public void testProduct() throws Exception { //Product p = productDao.selectByPrimaryKey(1L);
//System.out.println(p); //查询: 按照条件查询, 支持模糊查询, 分页 排序 指定字段查, 查询总数
ProductQuery productQuery = new ProductQuery();
//模糊查询
//productQuery.createCriteria().andNameLike("%" + "显瘦" + "%");
//设置条件精准查询
//productQuery.createCriteria().andNameEqualTo("2016最新款的缔彩枫2015秋冬新款时尚英伦风大衣简约收腰显瘦灰色中长款毛呢外套 灰色 S")
//.andBrandIdEqualTo(3L); //排序 id desc
productQuery.setOrderByClause("id desc"); //分页
productQuery.setPageNo(1);
productQuery.setPageSize(3); //根据指定字段查询
productQuery.setFields("id, name"); List<Product> products = productDao.selectByExample(productQuery);
for (Product product : products) {
System.out.println(product);
} //查询总条数
productDao.countByExample(productQuery); //保存
//productDao.insertSelective(product); //更新
//productDao.updateByExampleSelective(record, example);
//productDao.updateByPrimaryKeySelective(record);
} }

测试类就是如上, 如果对于dao中的方法中的参数不是很详细, 那么就可以直接看dao.xml中的sql语句, 这样就可以一目了然了.
这里只是做个简单的总结, 由于dao和bean全都是自动生成的, 所以里面的代码还有必要再去多看两眼的.