在Dao层,通过数据库表反向生成,可以节省我们很多的精力,把更多的精力投入复杂的业务中。
数据库表反向生成,指的是通过数据库如mysql中的库表schema生成dao层读写表的基础代码,包括model(entity)和dao(mapper)。
在本文中我先介绍java中mybatis-generator的反向生成。我们在下一篇文章中会介绍django中ORM的反向生成。
mybatis-generator的反向生成有两种方式
1)源码打包生成mybatis-generator.jar,通过执行jar来生成代码,然后把代码拷贝到工程
2)直接跟编辑器集成,例如IDEA。
我们只说明第二种方式。
1、在IDEA中创建一个maven工程
2、在maven工程的pom文件中添加mybatis-generator-maven-plugin插件
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.2
true
true
3、在src/main/resources目录下创建两个配置文件,generatorConfig.xml和generator.properties
generatorConfig.xml文件
内容请看注释,
/p>
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
generator.properties文件
这个主要配置的是你的驱动程序和数据库链接,mybatis将去配置的数据库中扫描要生成的表。
jdbc.driverLocation=/Users/didi/.m2/repository/mysql/mysql-connector-java/5.1.40/mysql-connector-java-5.1.40.jar
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://localhost:3306/jazz?useUnicode=true&characterEncoding=utf-8
jdbc.userId=root
jdbc.password=123456
4、在IDEA中添加Run选项,使用mybatis-generator-maven-plugin

配置如下
1)Name写generator会在run菜单生成一个名叫generator的选项;
2)CommandLine写要执行的命令,mybatis-generator:generate -e
3)working directory写你pom所在的工程,我这里是区分模块开发的,所以在dao模块下。

5、run -> generator执行
这样就会生成对应的代码了
我两张表的建表语句如下:
CREATE TABLE`hiveTable` (
`id`int(100) NOT NULL AUTO_INCREMENT COMMENT '库表唯一Id',
`dbName`VARCHAR(100) COMMENT '库名',
`tableName`VARCHAR(100) COMMENT '表名',
`location`VARCHAR(500) COMMENT '路径',
`createTime`DATETIME COMMENT '创建时间',
`updateTime`DATETIME COMMENT '更新时间',PRIMARY KEY(`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;CREATE TABLE`hiveLocation` (
`id`int(100) NOT NULL AUTO_INCREMENT COMMENT '路径唯一Id',
`location`VARCHAR(500) COMMENT '路径',
`size`INT(10) COMMENT '大小',
`createTime`DATETIME COMMENT '创建时间',
`updateTime`DATETIME COMMENT '更新时间',PRIMARY KEY(`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
生成的代码如图

我们展示一些生成的代码:
HiveTable.java
packagecom.xiaoju.dqa.jazz.dao.model;importjava.util.Date;public classHiveTable {/*** This field was generated by MyBatis Generator.
* This field corresponds to the database column hiveTable.id
*
* @mbggenerated*/
privateInteger id;/*** This field was generated by MyBatis Generator.
* This field corresponds to the database column hiveTable.dbName
*
* @mbggenerated*/
privateString dbname;/*** This field was generated by MyBatis Generator.
* This field corresponds to the database column hiveTable.tableName
*
* @mbggenerated*/
privateString tablename;/*** This field was generated by MyBatis Generator.
* This field corresponds to the database column hiveTable.location
*
* @mbggenerated*/
privateString location;/*** This field was generated by MyBatis Generator.
* This field corresponds to the database column hiveTable.createTime
*
* @mbggenerated*/
privateDate createtime;/*** This field was generated by MyBatis Generator.
* This field corresponds to the database column hiveTable.updateTime
*
* @mbggenerated*/
privateDate updatetime;/*** This method was generated by MyBatis Generator.
* This method corresponds to the database table hiveTable
*
* @mbggenerated*/
publicHiveTable(Integer id, String dbname, String tablename, String location, Date createtime, Date updatetime) {this.id =id;this.dbname =dbname;this.tablename =tablename;this.location =location;this.createtime =createtime;this.updatetime =updatetime;
}/*** This method was generated by MyBatis Generator.
* This method returns the value of the database column hiveTable.id
*
*@returnthe value of hiveTable.id
*
* @mbggenerated*/
publicInteger getId() {returnid;
}/*** This method was generated by MyBatis Generator.
* This method returns the value of the database column hiveTable.dbName
*
*@returnthe value of hiveTable.dbName
*
* @mbggenerated*/
publicString getDbname() {returndbname;
}/*** This method was generated by MyBatis Generator.
* This method returns the value of the database column hiveTable.tableName
*
*@returnthe value of hiveTable.tableName
*
* @mbggenerated*/
publicString getTablename() {returntablename;
}/*** This method was generated by MyBatis Generator.
* This method returns the value of the database column hiveTable.location
*
*@returnthe value of hiveTable.location
*
* @mbggenerated*/
publicString getLocation() {returnlocation;
}/*** This method was generated by MyBatis Generator.
* This method returns the value of the database column hiveTable.createTime
*
*@returnthe value of hiveTable.createTime
*
* @mbggenerated*/
publicDate getCreatetime() {returncreatetime;
}/*** This method was generated by MyBatis Generator.
* This method returns the value of the database column hiveTable.updateTime
*
*@returnthe value of hiveTable.updateTime
*
* @mbggenerated*/
publicDate getUpdatetime() {returnupdatetime;
}
}
HiveTableMapper.java
packagecom.xiaoju.dqa.jazz.dao.mapper;importcom.xiaoju.dqa.jazz.dao.model.HiveTable;import org.apache.ibatis.annotations.*;
@Mapperpublic interfaceHiveTableMapper {/*** This method was generated by MyBatis Generator.
* This method corresponds to the database table hiveTable
*
* @mbggenerated*/@Delete({"delete from hiveTable","where id = #{id,jdbcType=INTEGER}"})intdeleteByPrimaryKey(Integer id);/*** This method was generated by MyBatis Generator.
* This method corresponds to the database table hiveTable
*
* @mbggenerated*/@Insert({"insert into hiveTable (id, dbName, ","tableName, location, ","createTime, updateTime)","values (#{id,jdbcType=INTEGER}, #{dbname,jdbcType=VARCHAR}, ","#{tablename,jdbcType=VARCHAR}, #{location,jdbcType=VARCHAR}, ","#{createtime,jdbcType=TIMESTAMP}, #{updatetime,jdbcType=TIMESTAMP})"})intinsert(HiveTable record);/*** This method was generated by MyBatis Generator.
* This method corresponds to the database table hiveTable
*
* @mbggenerated*/
intinsertSelective(HiveTable record);/*** This method was generated by MyBatis Generator.
* This method corresponds to the database table hiveTable
*
* @mbggenerated*/@Select({"select","id, dbName, tableName, location, createTime, updateTime","from hiveTable","where id = #{id,jdbcType=INTEGER}"})
@ResultMap("BaseResultMap")
HiveTable selectByPrimaryKey(Integer id);/*** This method was generated by MyBatis Generator.
* This method corresponds to the database table hiveTable
*
* @mbggenerated*/
intupdateByPrimaryKeySelective(HiveTable record);/*** This method was generated by MyBatis Generator.
* This method corresponds to the database table hiveTable
*
* @mbggenerated*/@Update({"update hiveTable","set dbName = #{dbname,jdbcType=VARCHAR},","tableName = #{tablename,jdbcType=VARCHAR},","location = #{location,jdbcType=VARCHAR},","createTime = #{createtime,jdbcType=TIMESTAMP},","updateTime = #{updatetime,jdbcType=TIMESTAMP}","where id = #{id,jdbcType=INTEGER}"})intupdateByPrimaryKey(HiveTable record);
}
HiveTableMapper.xml
id, dbName, tableName, location, createTime, updateTime
insert into hiveTable
id,
dbName,
tableName,
location,
createTime,
updateTime,
#{id,jdbcType=INTEGER},
#{dbname,jdbcType=VARCHAR},
#{tablename,jdbcType=VARCHAR},
#{location,jdbcType=VARCHAR},
#{createtime,jdbcType=TIMESTAMP},
#{updatetime,jdbcType=TIMESTAMP},
update hiveTable
dbName = #{dbname,jdbcType=VARCHAR},
tableName = #{tablename,jdbcType=VARCHAR},
location = #{location,jdbcType=VARCHAR},
createTime = #{createtime,jdbcType=TIMESTAMP},
updateTime = #{updatetime,jdbcType=TIMESTAMP},
where id = #{id,jdbcType=INTEGER}
想让xml文件生效,你可以在创建数据源的时候加入xml文件的路径
例如其中的bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis-mapper/*.xml"));
packagecom.xiaoju.dqa.jazz.dao.configuration;importorg.apache.ibatis.session.SqlSessionFactory;importorg.mybatis.spring.SqlSessionFactoryBean;importorg.mybatis.spring.SqlSessionTemplate;importorg.mybatis.spring.annotation.MapperScan;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.Primary;importorg.springframework.core.io.support.PathMatchingResourcePatternResolver;importorg.springframework.jdbc.datasource.DataSourceTransactionManager;importjavax.sql.DataSource;
@Configuration
@MapperScan(basePackages= "com.xiaoju.dqa.jazz.dao.mapper", sqlSessionTemplateRef = "jazzSqlSessionTemplate")public classJazzDataSource {
@Bean(name= "jazzData")
@ConfigurationProperties(prefix= "spring.datasource.jazz")
@PrimarypublicDataSource jazzData() {returnDataSourceBuilder.create().build();
}
@Bean(name= "jazzSqlSessionFactory")
@Primarypublic SqlSessionFactory jazzSqlSessionFactory(@Qualifier("jazzData") DataSource dataSource) throwsException {
SqlSessionFactoryBean bean= newSqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis-mapper/*.xml"));returnbean.getObject();
}
@Bean(name= "jazzTransactionManager")
@Primarypublic DataSourceTransactionManager jazzTransactionManager(@Qualifier("jazzData") DataSource dataSource) {return newDataSourceTransactionManager(dataSource);
}
@Bean(name= "jazzSqlSessionTemplate")
@Primarypublic SqlSessionTemplate jazzSqlSessionTemplate(@Qualifier("jazzSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throwsException {return newSqlSessionTemplate(sqlSessionFactory);
}
}