zoukankan      html  css  js  c++  java
  • Mybatis逆向工程构建项目实例.

    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, 数据库表结构


    2,将逆向工程导入到Eclipse中


    3,使用逆向工程
    逆向工程目录结构:


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

    复制代码
     1 import java.io.File;
     2 import java.util.ArrayList;
     3 import java.util.List;
     4 
     5 import org.mybatis.generator.api.MyBatisGenerator;
     6 import org.mybatis.generator.config.Configuration;
     7 import org.mybatis.generator.config.xml.ConfigurationParser;
     8 import org.mybatis.generator.internal.DefaultShellCallback;
     9 
    10 public class GeneratorSqlmap {
    11 
    12     public void generator() throws Exception{
    13 
    14         List<String> warnings = new ArrayList<String>();
    15         boolean overwrite = true;
    16         File configFile = new File("generatorConfig.xml"); 
    17         ConfigurationParser cp = new ConfigurationParser(warnings);
    18         Configuration config = cp.parseConfiguration(configFile);
    19         DefaultShellCallback callback = new DefaultShellCallback(overwrite);
    20         MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
    21                 callback, warnings);
    22         myBatisGenerator.generate(null);
    23 
    24     } 
    25     public static void main(String[] args) throws Exception {
    26         try {
    27             GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
    28             generatorSqlmap.generator();
    29         } catch (Exception e) {
    30             e.printStackTrace();
    31         }
    32         
    33     }
    34 
    35 }
    复制代码


    下面就是看下generatorConfig.xml中的一些配置:

    复制代码
      1 <?xml version="1.0" encoding="UTF-8"?>
      2 <!DOCTYPE generatorConfiguration
      3   PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
      4   "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
      5 
      6 <generatorConfiguration>
      7     <context id="testTables" targetRuntime="MyBatis3">
      8     
      9         <!-- JavaBean 实现 序列化 接口 -->
     10         <plugin type="org.mybatis.generator.plugins.SerializablePlugin">
     11         </plugin>
     12         <!-- genenat entity时,生成toString -->
     13         <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
     14         <!-- 自定义物理分页  可生成支持Mysql数据的limit  不支持Oracle -->
     15         <plugin type="org.mybatis.generator.plugins.page.PaginationPlugin" />
     16         <!-- 自定义查询指定字段  -->
     17         <plugin type="org.mybatis.generator.plugins.field.FieldsPlugin" />
     18         <!-- 开启支持内存分页   可生成 支持内存分布的方法及参数  
     19         <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin" />
     20         -->
     21         <!-- generate entity时,生成hashcode和equals方法
     22         <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin" />
     23          -->
     24         <!-- 此处是将Example改名为Criteria 当然 想改成什么都行~    -->      
     25         <plugin type="org.mybatis.generator.plugins.RenameExampleClassPlugin">  
     26             <property name="searchString" value="Example$" />
     27             <!-- 替换后
     28             <property name="replaceString" value="Criteria" />  
     29              -->
     30             <property name="replaceString" value="Query" />
     31         </plugin>  
     32         <!-- 此处是将UserMapper.xml改名为UserDao.xml 当然 想改成什么都行~ -->        
     33         <plugin type="org.mybatis.generator.plugins.rename.RenameSqlMapperPlugin">  
     34             <property name="searchString" value="Mapper" />
     35             <property name="replaceString" value="Dao" />
     36         </plugin>  
     37          
     38         <!-- 此处是将UserMapper改名为UserDao 接口 当然 想改成什么都行~  -->        
     39         <plugin type="org.mybatis.generator.plugins.rename.RenameJavaMapperPlugin">  
     40             <property name="searchString" value="Mapper$" />
     41             <property name="replaceString" value="Dao" />
     42         </plugin>  
     43         
     44  
     45         
     46         <commentGenerator type="org.mybatis.generator.plugins.comment.MyCommentGenerator">
     47             <!-- 是否去除自动生成的注释 true:是 : false:否 
     48             <property name="suppressAllComments" value="true" />
     49             -->
     50         </commentGenerator>
     51         
     52         <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
     53         <jdbcConnection driverClass="com.mysql.jdbc.Driver"
     54             connectionURL="jdbc:mysql://localhost:3306/babasport" userId="root"
     55             password="123456">
     56         </jdbcConnection>
     57         <!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
     58             connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg" 
     59             userId="yycg"
     60             password="yycg">
     61         </jdbcConnection> -->
     62 
     63         <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 
     64             NUMERIC 类型解析为java.math.BigDecimal -->
     65         <javaTypeResolver>
     66             <property name="forceBigDecimals" value="false" />
     67         </javaTypeResolver>
     68 
     69 
     70         <!-- targetProject:生成PO类的位置 -->
     71         <javaModelGenerator targetPackage="cn.itcast.core.bean"
     72             targetProject=".src">
     73             <!-- enableSubPackages:是否让schema作为包的后缀 -->
     74             <property name="enableSubPackages" value="false" />
     75             <!-- 从数据库返回的值被清理前后的空格 -->
     76             <property name="trimStrings" value="true" />
     77         </javaModelGenerator>
     78 
     79         <!-- targetProject:mapper映射文件生成的位置 -->
     80         <sqlMapGenerator targetPackage="cn.itcast.core.dao" 
     81             targetProject=".src">
     82             <!-- enableSubPackages:是否让schema作为包的后缀 -->
     83             <property name="enableSubPackages" value="false" />
     84         </sqlMapGenerator>
     85         <!-- targetPackage:mapper接口生成的位置 -->
     86         <javaClientGenerator type="XMLMAPPER"
     87             targetPackage="cn.itcast.core.dao" 
     88             targetProject=".src">
     89             <!-- enableSubPackages:是否让schema作为包的后缀 -->
     90             <property name="enableSubPackages" value="true" />
     91         </javaClientGenerator>
     92         
     93         <!-- 指定数据库表 -->
     94         <!-- 用户模块表  -->
     95         <table schema="" tableName="bbs_buyer" domainObjectName="user.Buyer"/>
     96         
     97         <!-- 商品模块表 -->
     98         <table schema="" tableName="bbs_product" domainObjectName="product.Product">
     99             <!-- 商品介绍 大字段映射 -->
    100             <columnOverride column="description" javaType="String" jdbcType="VARCHAR" />
    101             <!-- 包装清单 大字段映射 -->
    102             <columnOverride column="package_list" javaType="String" jdbcType="VARCHAR" />
    103             <!-- 商品图片 大字段映射 -->
    104             <columnOverride column="img_url" javaType="String" jdbcType="VARCHAR" />
    105         </table>
    106         <table schema="" tableName="bbs_brand" domainObjectName="product.Brand"/>
    107         <table schema="" tableName="bbs_Color" domainObjectName="product.Color"/>
    108         <table schema="" tableName="bbs_sku" domainObjectName="product.Sku"/>
    109         
    110         <!-- 订单模块表 -->
    111         <table schema="" tableName="bbs_order" domainObjectName="order.Order">
    112             <!-- 支付方式 0:到付 1:在线 2:邮局 3:公司转帐 -->
    113             <columnOverride column="payment_way" javaType="Integer"/>
    114             <!-- 货到付款方式.1现金,2POS刷卡 -->
    115             <columnOverride column="payment_cash" javaType="Integer" />
    116             <!-- 送货时间 -->
    117             <columnOverride column="delivery" javaType="Integer"/>
    118             <!-- 支付状态 :0到付1待付款,2已付款,3待退款,4退款成功,5退款失败 -->
    119             <columnOverride column="is_paiy" javaType="Integer"/>
    120             <!-- 订单状态 0:提交订单 1:仓库配货 2:商品出库 3:等待收货 4:完成 5待退货 6已退货 -->
    121             <columnOverride column="state" javaType="Integer"/>
    122             <!-- 订单状态 默认Boolean -->
    123             <columnOverride column="order_state" javaType="Integer"/>
    124         </table>
    125         <table schema="" tableName="bbs_detail" domainObjectName="order.Detail"/>
    126         
    127         <!-- 指定数据库所有表  
    128         <table schema="" tableName="%"/>
    129         -->
    130         
    131         <!-- 有些表的字段需要指定java类型
    132          <table schema="" tableName="">
    133             <columnOverride column="" javaType="" />
    134         </table> -->
    135     </context>
    136 </generatorConfiguration>
    复制代码

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

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

    复制代码
     1 package cn.itcast;
     2 
     3 import java.util.Date;
     4 import java.util.List;
     5 
     6 import javax.annotation.Resource;
     7 
     8 import org.junit.Test;
     9 import org.junit.runner.RunWith;
    10 import org.springframework.beans.factory.annotation.Autowired;
    11 import org.springframework.test.context.ContextConfiguration;
    12 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    13 
    14 import cn.itcast.core.bean.TestTb;
    15 import cn.itcast.core.bean.product.Product;
    16 import cn.itcast.core.bean.product.ProductQuery;
    17 import cn.itcast.core.dao.TestTbDao;
    18 import cn.itcast.core.dao.product.ProductDao;
    19 import cn.itcast.core.service.TestTbService;
    20 
    21 @RunWith(SpringJUnit4ClassRunner.class)
    22 @ContextConfiguration(locations = {"classpath:application-context.xml"})
    23 public class TestProduct {
    24 
    25     @Resource
    26     private ProductDao productDao;
    27     
    28     @Test
    29     public void testProduct() throws Exception {
    30         
    31         //Product p = productDao.selectByPrimaryKey(1L);
    32         //System.out.println(p);
    33         
    34         //查询: 按照条件查询, 支持模糊查询, 分页 排序  指定字段查, 查询总数
    35         ProductQuery productQuery = new ProductQuery();
    36         //模糊查询
    37         //productQuery.createCriteria().andNameLike("%" + "显瘦" + "%");
    38         //设置条件精准查询
    39         //productQuery.createCriteria().andNameEqualTo("2016最新款的缔彩枫2015秋冬新款时尚英伦风大衣简约收腰显瘦灰色中长款毛呢外套 灰色 S")
    40              //.andBrandIdEqualTo(3L);
    41         
    42         //排序 id desc
    43         productQuery.setOrderByClause("id desc");
    44         
    45         //分页
    46         productQuery.setPageNo(1);
    47         productQuery.setPageSize(3);
    48         
    49         //根据指定字段查询
    50         productQuery.setFields("id, name");
    51         
    52         List<Product> products = productDao.selectByExample(productQuery);
    53         for (Product product : products) {
    54             System.out.println(product);
    55         }
    56         
    57         //查询总条数
    58         productDao.countByExample(productQuery);
    59         
    60         //保存
    61         //productDao.insertSelective(product);
    62         
    63         //更新
    64         //productDao.updateByExampleSelective(record, example);
    65         //productDao.updateByPrimaryKeySelective(record);
    66     }
    67     
    68 }
    复制代码

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

  • 相关阅读:
    遍历数据类型数组方式
    for 循环 和for..in循环遍历数组 的区别
    多个区域内有相同属性名称子元素,同一区域内 操作DOM子集 使用$("选择器",context)方法
    CSS 使用技巧
    JavaScript 动态加载页面 js文件
    angular2环境配置
    在路上●我的年青●逐步前进
    ARM v8-A 系列CPU的MMU隐射分析
    ARM Cortex-A53 Cache与内存的映射关系以及Cache的一致性分析
    二维图像的投影和图像重建分析之傅里叶变换法
  • 原文地址:https://www.cnblogs.com/du-0210/p/8426504.html
Copyright © 2011-2022 走看看