MyBatis MyBatis Generator入门

  一、MGB功能简介

  MyBatis Generator是一个代码生成工具。

  MBG是如何运行的呢?它会检查所连接到的数据库的一个或者多个table,然后生成可用来访问这些table的构建(Java代码、XML文件等)。这减少了一开始在使用MyBatis与数据库连接交互时设置对象和配置文件的种种繁冗的操作。

  MBG目的是,对多数在数据库table上进行的简单的CRUD操作,都能自动生成相应Java代码以及映射文件。但是对于JOIN查询、存储过程等高级SQL操作,仍需要手动配置。

 

  二、MBG可以生成什么

  2.1 与一个表的结构对应的Java POJOs。

  这可能包括了:

  • a class to match the primary key of the table (if there is a primary key)
  • a class to match the non-primary key fields of the table (except BLOB fields)
  • a class to include the BLOB fields of a table (if the table has BLOB fields)
  • a class to enable dynamic selects, updates, and deletes

  这些类之间会有适当的继承关系(意思是一个表能生成多个类?)。

  通过修改配置,可以产生不同的继承关系。例如,如果需要,可以选择为每个表生成一个域对象。

 

  2.2 兼容MyBatis/iBATIS的SQL Map XML文件。

   MBG为一个configuration中的每个表上的简单CRUD函数生成相应的SQL。

  可以生成的SQL语句有:

  • insert
  • update by primary key
  • update by example (using a dynamic where clause)
  • delete by primary key
  • delete by example (using a dynamic where clause)
  • select by primary key
  • select by example (using a dynamic where clause)
  • count by example

  结果是依据表的结构而变化的,如果table没有主键,自然就不会生成通过主键来执行的操作。

  2.3 适当使用上述对象的Java Client类(貌似是DAO层的东西)

  Java Client类的生成是可选的,MBG将为MyBatis 3.x生成以下类型的Java Clients:

  • A mapper interface that works with the MyBatis 3.x mapper infrastructure;

  

  MBG will generate Java clients of the following types for iBATIS 2.x:

  • DAOs that conform to the Spring framework
  • DAOs that only use the iBATIS SQL mapping API. These DAOs can be generated in two varieties: supplying the SqlMapClient through either constructor or setter injection.
  • DAOs that conform to the iBATIS DAO Framework (an optional part of iBATIS, this framework is now deprecated and we suggest that you use the Spring framework instead)

  三、在迭代的环境中运行MBG

  MyBatis Generator为在迭代开发的环境中能够良好运行而设计,它可以作为Ant的task,或Maven的plugin,包含在持续构建环境中。

  当以迭代方式运行MBG时,需要注意的重要事项:

 1、如果存在与新生成的XML文件同名的现有文件,MBG将自动合并XML文件。

  MBG不会覆盖你对它生成的XML文件所做的任何自定义更改。您可以一次又一次地运行它,而不必担心丢失对XML的自定义更改。MBG将替换上次运行中生成的任何XML元素。

 2、MBG不会合并Java文件

  它既可以覆盖现有文件,也可以用不同的惟一名称保存新生成的文件。

  如果你对生成的Java文件进行更改并迭代运行MBG,则必须手工合并更改这些Java文件。

  当作为Eclipse插件运行时,MBG可以自动合并Java文件。

  四、MBG的依赖关系

  除了JRE之外,MBG没有任何依赖项。要求JRE 6.0或以上版本。

  MBG_1.3.6的运行要求Java 8,该版本可以生成基于 MyBatis Dynamic SQL的代码,当然默认是不开启的。

  不同版本的特性请看(What's New in MyBatis Generator)。

  此外,连接数据库所用的驱动(JDBC driver),必须实现DatabaseMetaData接口,特别是getColumns和getPrimaryKeys方法。

  

  

猜你喜欢

转载自www.cnblogs.com/bigbigbigo/p/10036114.html