在Dao層,經過數據庫表反向生成,能夠節省咱們不少的精力,把更多的精力投入複雜的業務中。html
數據庫表反向生成,指的是經過數據庫如mysql中的庫表schema生成dao層讀寫表的基礎代碼,包括model(entity)和dao(mapper)。java
在本文中我先介紹java中mybatis-generator的反向生成。咱們在下一篇文章中會介紹django中ORM的反向生成。mysql
mybatis-generator的反向生成有兩種方式spring
1)源碼打包生成mybatis-generator.jar,經過執行jar來生成代碼,而後把代碼拷貝到工程sql
2)直接跟編輯器集成,例如IDEA。數據庫
咱們只說明第二種方式。apache
一、在IDEA中建立一個maven工程django
二、在maven工程的pom文件中添加mybatis-generator-maven-plugin插件session
<build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> </plugins> </build>
三、在src/main/resources目錄下建立兩個配置文件,generatorConfig.xml和generator.propertiesmybatis
generatorConfig.xml文件
內容請看註釋,<table>中配置的是你要掃描的表。
<?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> <!--導入屬性配置 --> <properties resource="generator.properties"></properties> <!--指定特定數據庫的jdbc驅動jar包的位置 --> <classPathEntry location="${jdbc.driverLocation}"/> <context id="default" targetRuntime="MyBatis3"> <!-- optional,旨在建立class時,對註釋進行控制 --> <commentGenerator> <property name="suppressDate" value="true" /> </commentGenerator> <!--jdbc的數據庫鏈接 --> <jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbc.connectionURL}" userId="${jdbc.userId}" password="${jdbc.password}"> </jdbcConnection> <!-- 非必需,類型處理器,在數據庫類型和java類型之間的轉換控制--> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- Model模型生成器,用來生成含有主鍵key的類,記錄類 以及查詢Example類 targetPackage 指定生成的model生成所在的包名 targetProject 指定在該項目下所在的路徑 --> <javaModelGenerator targetPackage="com.xiaoju.dqa.jazz.dao.model" targetProject="src/main/java"> <!-- 是否對model添加 構造函數 --> <property name="constructorBased" value="true"/> <!-- 是否容許子包,即targetPackage.schemaName.tableName --> <property name="enableSubPackages" value="false"/> <!-- 創建的Model對象是否 不可改變 即生成的Model對象不會有 setter方法,只有構造方法 --> <property name="immutable" value="true"/> <!-- 是否對類CHAR類型的列的數據進行trim操做 --> <property name="trimStrings" value="true"/> </javaModelGenerator> <!--Mapper映射文件生成所在的目錄 爲每個數據庫的表生成對應的SqlMap文件 --> <sqlMapGenerator targetPackage="mybatis-mapper" targetProject="src/main/resources"> <property name="enableSubPackages" value="false"/> </sqlMapGenerator> <!-- 客戶端代碼,生成易於使用的針對Model對象和XML配置文件 的代碼 type="ANNOTATEDMAPPER",生成Java Model 和基於註解的Mapper對象 type="MIXEDMAPPER",生成基於註解的Java Model 和相應的Mapper對象 type="XMLMAPPER",生成SQLMap XML文件和獨立的Mapper接口 --> <javaClientGenerator targetPackage="com.xiaoju.dqa.jazz.dao.mapper" targetProject="src/main/java" type="MIXEDMAPPER"> <property name="enableSubPackages" value=""/> <!-- 定義Maper.java 源代碼中的ByExample() 方法的可視性,可選的值有: public; private; protected; default 注意:若是 targetRuntime="MyBatis3",此參數被忽略 --> <property name="exampleMethodVisibility" value=""/> <!-- 方法名計數器 Important note: this property is ignored if the target runtime is MyBatis3. --> <property name="methodNameCalculator" value=""/> <!-- 爲生成的接口添加父接口 --> <property name="rootInterface" value=""/> </javaClientGenerator> <table tableName="hiveTable" domainObjectName="HiveTable" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> </table> <table tableName="hiveLocation" domainObjectName="HiveLocation" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> </table> </context> </generatorConfiguration>
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
四、在IDEA中添加Run選項,使用mybatis-generator-maven-plugin
配置以下
1)Name寫generator會在run菜單生成一個名叫generator的選項;
2)CommandLine寫要執行的命令,mybatis-generator:generate -e
3)working directory寫你pom所在的工程,我這裏是區分模塊開發的,因此在dao模塊下。
五、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
package com.xiaoju.dqa.jazz.dao.model; import java.util.Date; public class HiveTable { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column hiveTable.id * * @mbggenerated */ private Integer id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column hiveTable.dbName * * @mbggenerated */ private String dbname; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column hiveTable.tableName * * @mbggenerated */ private String tablename; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column hiveTable.location * * @mbggenerated */ private String location; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column hiveTable.createTime * * @mbggenerated */ private Date createtime; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column hiveTable.updateTime * * @mbggenerated */ private Date updatetime; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table hiveTable * * @mbggenerated */ public HiveTable(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 * * @return the value of hiveTable.id * * @mbggenerated */ public Integer getId() { return id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column hiveTable.dbName * * @return the value of hiveTable.dbName * * @mbggenerated */ public String getDbname() { return dbname; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column hiveTable.tableName * * @return the value of hiveTable.tableName * * @mbggenerated */ public String getTablename() { return tablename; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column hiveTable.location * * @return the value of hiveTable.location * * @mbggenerated */ public String getLocation() { return location; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column hiveTable.createTime * * @return the value of hiveTable.createTime * * @mbggenerated */ public Date getCreatetime() { return createtime; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column hiveTable.updateTime * * @return the value of hiveTable.updateTime * * @mbggenerated */ public Date getUpdatetime() { return updatetime; } }
HiveTableMapper.java
package com.xiaoju.dqa.jazz.dao.mapper; import com.xiaoju.dqa.jazz.dao.model.HiveTable; import org.apache.ibatis.annotations.*; @Mapper public interface HiveTableMapper { /** * 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}" }) int deleteByPrimaryKey(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})" }) int insert(HiveTable record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table hiveTable * * @mbggenerated */ int insertSelective(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 */ int updateByPrimaryKeySelective(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}" }) int updateByPrimaryKey(HiveTable record); }
HiveTableMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.xiaoju.dqa.jazz.dao.mapper.HiveTableMapper" > <resultMap id="BaseResultMap" type="com.xiaoju.dqa.jazz.dao.model.HiveTable" > <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator, do not modify. --> <constructor > <idArg column="id" jdbcType="INTEGER" javaType="java.lang.Integer" /> <arg column="dbName" jdbcType="VARCHAR" javaType="java.lang.String" /> <arg column="tableName" jdbcType="VARCHAR" javaType="java.lang.String" /> <arg column="location" jdbcType="VARCHAR" javaType="java.lang.String" /> <arg column="createTime" jdbcType="TIMESTAMP" javaType="java.util.Date" /> <arg column="updateTime" jdbcType="TIMESTAMP" javaType="java.util.Date" /> </constructor> </resultMap> <sql id="Base_Column_List" > <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator, do not modify. --> id, dbName, tableName, location, createTime, updateTime </sql> <insert id="insertSelective" parameterType="com.xiaoju.dqa.jazz.dao.model.HiveTable" > <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator, do not modify. --> insert into hiveTable <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="dbname != null" > dbName, </if> <if test="tablename != null" > tableName, </if> <if test="location != null" > location, </if> <if test="createtime != null" > createTime, </if> <if test="updatetime != null" > updateTime, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=INTEGER}, </if> <if test="dbname != null" > #{dbname,jdbcType=VARCHAR}, </if> <if test="tablename != null" > #{tablename,jdbcType=VARCHAR}, </if> <if test="location != null" > #{location,jdbcType=VARCHAR}, </if> <if test="createtime != null" > #{createtime,jdbcType=TIMESTAMP}, </if> <if test="updatetime != null" > #{updatetime,jdbcType=TIMESTAMP}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.xiaoju.dqa.jazz.dao.model.HiveTable" > <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator, do not modify. --> update hiveTable <set > <if test="dbname != null" > dbName = #{dbname,jdbcType=VARCHAR}, </if> <if test="tablename != null" > tableName = #{tablename,jdbcType=VARCHAR}, </if> <if test="location != null" > location = #{location,jdbcType=VARCHAR}, </if> <if test="createtime != null" > createTime = #{createtime,jdbcType=TIMESTAMP}, </if> <if test="updatetime != null" > updateTime = #{updatetime,jdbcType=TIMESTAMP}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> </mapper>
想讓xml文件生效,你能夠在建立數據源的時候加入xml文件的路徑
例如其中的bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis-mapper/*.xml"));
package com.xiaoju.dqa.jazz.dao.configuration; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource; @Configuration @MapperScan(basePackages = "com.xiaoju.dqa.jazz.dao.mapper", sqlSessionTemplateRef = "jazzSqlSessionTemplate") public class JazzDataSource { @Bean(name = "jazzData") @ConfigurationProperties(prefix = "spring.datasource.jazz") @Primary public DataSource jazzData() { return DataSourceBuilder.create().build(); } @Bean(name = "jazzSqlSessionFactory") @Primary public SqlSessionFactory jazzSqlSessionFactory(@Qualifier("jazzData") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis-mapper/*.xml")); return bean.getObject(); } @Bean(name = "jazzTransactionManager") @Primary public DataSourceTransactionManager jazzTransactionManager(@Qualifier("jazzData") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "jazzSqlSessionTemplate") @Primary public SqlSessionTemplate jazzSqlSessionTemplate(@Qualifier("jazzSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } }