使用MyBatis Generator自动生成实体、mapper和dao层
通过MyBatis Generator可以自动生成实体、mapper和dao层,记录一下怎么用的。
主要步骤:
关于mybatis从数据库反向生成实体、DAO、mapper:
参考文章:http://www.cnblogs.com/wangkeai/p/6934683.html
第一种方式:main方法运行(推荐)
1.在pom.xml中加入插件依赖:
2.写mbgConfiguration.xml文件,jdbc.properties文件
3.写/SSM/src/main/java/main/GenMain.java main方法
4.运行main函数,刷新
具体步骤:
1.在pom.xml中加入插件依赖(需要mybatis的包和反向生成的包):
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.4</version> </dependency> <!-- mybatis-generator-core 反向生成java代码--> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency>
2、写mbgConfiguration.xml文件,jdbc.properties文件
mbgConfiguration.xml:里面的一些配置也是“因人而异”哦,需要适当修改。文件最后<table></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"> <!-- 第一种mybatis逆向生成xml配置 --> <generatorConfiguration> <properties resource="jdbc.properties" /> <context id="sqlserverTables" targetRuntime="MyBatis3"> <!-- 生成的pojo,将implements Serializable--> <plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin> <commentGenerator> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <!-- 数据库链接URL、用户名、密码 --> <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"> </jdbcConnection> <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer true,把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 生成model模型,对应的包路径,以及文件存放路径(targetProject),targetProject可以指定具体的路径,如./src/main/java, 也可以使用“MAVEN”来自动生成,这样生成的代码会在target/generatord-source目录下 --> <!--<javaModelGenerator targetPackage="com.joey.mybaties.test.pojo" targetProject="MAVEN">--> <javaModelGenerator targetPackage="com.yyc.entity" targetProject="./src/main/java"> <property name="enableSubPackages" value="true"/> <!-- 从数据库返回的值被清理前后的空格 --> <property name="trimStrings" value="true" /> </javaModelGenerator> <!--对应的mapper.xml文件 --> <sqlMapGenerator targetPackage="mappers" targetProject="./src/main/resources"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 对应的Mapper接口类文件 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.yyc.dao" targetProject="./src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 列出要生成代码的所有表,这里配置的是不生成Example文件 --> <table tableName="user_t" domainObjectName="UserInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" > <property name="useActualColumnNames" value="false"/> </table> </context> </generatorConfiguration>
由于上面的文件中使用了数据库连接,所以还别忘了数据库的包(相信在准备好学习mybatis前,已经在pom.xml文件中准备好了这些相关依赖)
jdbc.properties:
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf8 jdbc.username=root jdbc.password=123 #定义初始连接数 initialSize=0 #定义最大连接数 maxActive=20 #定义最大空闲 maxIdle=20 #定义最小空闲 minIdle=1 #定义最长等待时间 maxWait=60000
3.写GenMain.java main方法
/** * */ package main; import java.io.File; import java.io.IOException; import java.sql.SQLException; 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.exception.InvalidConfigurationException; import org.mybatis.generator.exception.XMLParserException; import org.mybatis.generator.internal.DefaultShellCallback; /************************************** * @author E-mail:[email protected] * @version 创建时间:2017年6月23日 下午9:18:19 * 类说明: * mybatis****main函数 *************************************** */ public class GenMain { public static void main(String[] args) { List<String> warnings = new ArrayList<String>(); boolean overwrite = true;
//如果这里出现空指针,直接写绝对路径即可。 String genCfg = "/mbgConfiguration.xml"; File configFile = new File(GenMain.class.getResource(genCfg).getFile()); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = null; try { config = cp.parseConfiguration(configFile); } catch (IOException e) { e.printStackTrace(); } catch (XMLParserException e) { e.printStackTrace(); } DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = null; try { myBatisGenerator = new MyBatisGenerator(config, callback, warnings); } catch (InvalidConfigurationException e) { e.printStackTrace(); } try { myBatisGenerator.generate(null); } catch (SQLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
4、运行Main方法,刷新项目,就会在上面mbgConfiguration.xml中配置的对应文件的目录下生成实体,mapper,dao了。
第二种方式:maven插件运行
1.pom.xml配置插件
2.写generatorConfig.xml文件
3.运行
具体步骤:
1.pom.xml配置插件build节点下加入插件:也就是maven一般加入tomcat插件的地方。
<!-- 第二种方式数据库反向生成java --> <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>
2.写generatorConfig.xml文件,与mbgConfiguration.xml文件不同的是:文件名固定只能是generatorConfig,文件中要配置数据库连接驱动绝对路径,并且,数据库连接信息url,username,password等都要写固定<classPathEntry location="E:\MavenRepository\mysql\mysql-connector-java\5.1.38\mysql-connector-java-5.1.38.jar" />
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"> <!-- 第二种mybatis逆向生成xml配置 --> <generatorConfiguration> <!-- 需要指明数据库连接器的绝对路径 --> <classPathEntry location="E:\MavenRepository\mysql\mysql-connector-java\5.1.38\mysql-connector-java-5.1.38.jar" /> <context id="sqlserverTables" targetRuntime="MyBatis3"> <!-- 生成的pojo,将implements Serializable--> <plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin> <commentGenerator> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <!-- 数据库链接URL、用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/ssm" userId="root" password="123cy-coo.com"> </jdbcConnection> <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer true,把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 生成model模型,对应的包路径,以及文件存放路径(targetProject),targetProject可以指定具体的路径,如./src/main/java, 也可以使用“MAVEN”来自动生成,这样生成的代码会在target/generatord-source目录下 --> <!--<javaModelGenerator targetPackage="com.joey.mybaties.test.pojo" targetProject="MAVEN">--> <javaModelGenerator targetPackage="com.yyc.entity" targetProject="./src/main/java"> <property name="enableSubPackages" value="true"/> <!-- 从数据库返回的值被清理前后的空格 --> <property name="trimStrings" value="true" /> </javaModelGenerator> <!--对应的mapper.xml文件 --> <sqlMapGenerator targetPackage="mappers" targetProject="./src/main/resources"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 对应的Mapper接口类文件 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.yyc.dao" targetProject="./src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 列出要生成代码的所有表,这里配置的是不生成Example文件 --> <table tableName="user_t" domainObjectName="UserInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" > <property name="useActualColumnNames" value="false"/> </table> </context> </generatorConfiguration>
3.运行方法:在eclipse 中,选择pom.xml文件,击右键先择Run AS——>Maven Build… ——>在Goals框中输入:mybatis-generator:generate 运行即可。
因为第一种xml文件的配置比较灵活,不像第二种xml中还需要写死数据库驱动地址和连接信息,并且还要多加一个jar插件。所以推荐第一种方式
第4种方式:
Mybatis属于半自动ORM,在使用这个框架中,工作量最大的就是书写Mapping的映射文件,由于手动书写很容易出错,我们可以利用Mybatis-Generator来帮我们自动生成文件。
1、相关文件
关于Mybatis-Generator的下载可以到这个地址:https://github.com/mybatis/generator/releases
由于我使用的是Mysql数据库,这里需要在准备一个连接mysql数据库的驱动jar包
以下是相关文件截图:
和Hibernate逆向生成一样,这里也需要一个配置文件:
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 <generatorConfiguration> 6 <!--数据库驱动--> 7 <classPathEntry location="mysql-connector-java-5.0.8-bin.jar"/> 8 <context id="DB2Tables" targetRuntime="MyBatis3"> 9 <commentGenerator> 10 <property name="suppressDate" value="true"/> 11 <property name="suppressAllComments" value="true"/> 12 </commentGenerator> 13 <!--数据库链接地址账号密码--> 14 <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost/mymessages" userId="root" password="root"> 15 </jdbcConnection> 16 <javaTypeResolver> 17 <property name="forceBigDecimals" value="false"/> 18 </javaTypeResolver> 19 <!--生成Model类存放位置--> 20 <javaModelGenerator targetPackage="lcw.model" targetProject="src"> 21 <property name="enableSubPackages" value="true"/> 22 <property name="trimStrings" value="true"/> 23 </javaModelGenerator> 24 <!--生成映射文件存放位置--> 25 <sqlMapGenerator targetPackage="lcw.mapping" targetProject="src"> 26 <property name="enableSubPackages" value="true"/> 27 </sqlMapGenerator> 28 <!--生成Dao类存放位置--> 29 <javaClientGenerator type="XMLMAPPER" targetPackage="lcw.dao" targetProject="src"> 30 <property name="enableSubPackages" value="true"/> 31 </javaClientGenerator> 32 <!--生成对应表及类名--> 33 <table tableName="message" domainObjectName="Messgae" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> 34 </context> 35 </generatorConfiguration>
需要修改文件配置的地方我都已经把注释标注出来了,这里的相关路径(如数据库驱动包,生成对应的相关文件位置可以自定义)不能带有中文。
上面配置文件中的:
<table tableName="message" domainObjectName="Messgae" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
tableName和domainObjectName为必选项,分别代表数据库表名和生成的实力类名,其余的可以自定义去选择(一般情况下均为false)。
生成语句文件:
java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite
2、使用方法
在该目录按住Shift键,右键鼠标选择"在此处打开命令窗口",复制粘贴生成语句的文件代码即可。
看下效果图:
生成相关代码:
Message.java
1 package lcw.model; 2 3 public class Messgae { 4 private Integer id; 5 6 private String title; 7 8 private String describe; 9 10 private String content; 11 12 public Integer getId() { 13 return id; 14 } 15 16 public void setId(Integer id) { 17 this.id = id; 18 } 19 20 public String getTitle() { 21 return title; 22 } 23 24 public void setTitle(String title) { 25 this.title = title == null ? null : title.trim(); 26 } 27 28 public String getDescribe() { 29 return describe; 30 } 31 32 public void setDescribe(String describe) { 33 this.describe = describe == null ? null : describe.trim(); 34 } 35 36 public String getContent() { 37 return content; 38 } 39 40 public void setContent(String content) { 41 this.content = content == null ? null : content.trim(); 42 } 43 }
MessgaeMapper.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 3 <mapper namespace="lcw.dao.MessgaeMapper" > 4 <resultMap id="BaseResultMap" type="lcw.model.Messgae" > 5 <id column="id" property="id" jdbcType="INTEGER" /> 6 <result column="title" property="title" jdbcType="VARCHAR" /> 7 <result column="describe" property="describe" jdbcType="VARCHAR" /> 8 <result column="content" property="content" jdbcType="VARCHAR" /> 9 </resultMap> 10 <sql id="Base_Column_List" > 11 id, title, describe, content 12 </sql> 13 <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > 14 select 15 <include refid="Base_Column_List" /> 16 from message 17 where id = #{id,jdbcType=INTEGER} 18 </select> 19 <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > 20 delete from message 21 where id = #{id,jdbcType=INTEGER} 22 </delete> 23 <insert id="insert" parameterType="lcw.model.Messgae" > 24 insert into message (id, title, describe, 25 content) 26 values (#{id,jdbcType=INTEGER}, #{title,jdbcType=VARCHAR}, #{describe,jdbcType=VARCHAR}, 27 #{content,jdbcType=VARCHAR}) 28 </insert> 29 <insert id="insertSelective" parameterType="lcw.model.Messgae" > 30 insert into message 31 <trim prefix="(" suffix=")" suffixOverrides="," > 32 <if test="id != null" > 33 id, 34 </if> 35 <if test="title != null" > 36 title, 37 </if> 38 <if test="describe != null" > 39 describe, 40 </if> 41 <if test="content != null" > 42 content, 43 </if> 44 </trim> 45 <trim prefix="values (" suffix=")" suffixOverrides="," > 46 <if test="id != null" > 47 #{id,jdbcType=INTEGER}, 48 </if> 49 <if test="title != null" > 50 #{title,jdbcType=VARCHAR}, 51 </if> 52 <if test="describe != null" > 53 #{describe,jdbcType=VARCHAR}, 54 </if> 55 <if test="content != null" > 56 #{content,jdbcType=VARCHAR}, 57 </if> 58 </trim> 59 </insert> 60 <update id="updateByPrimaryKeySelective" parameterType="lcw.model.Messgae" > 61 update message 62 <set > 63 <if test="title != null" > 64 title = #{title,jdbcType=VARCHAR}, 65 </if> 66 <if test="describe != null" > 67 describe = #{describe,jdbcType=VARCHAR}, 68 </if> 69 <if test="content != null" > 70 content = #{content,jdbcType=VARCHAR}, 71 </if> 72 </set> 73 where id = #{id,jdbcType=INTEGER} 74 </update> 75 <update id="updateByPrimaryKey" parameterType="lcw.model.Messgae" > 76 update message 77 set title = #{title,jdbcType=VARCHAR}, 78 describe = #{describe,jdbcType=VARCHAR}, 79 content = #{content,jdbcType=VARCHAR} 80 where id = #{id,jdbcType=INTEGER} 81 </update> 82 </mapper>
MessgaeMapper.java
1 package lcw.dao; 2 3 import lcw.model.Messgae; 4 5 public interface MessgaeMapper { 6 int deleteByPrimaryKey(Integer id); 7 8 int insert(Messgae record); 9 10 int insertSelective(Messgae record); 11 12 Messgae selectByPrimaryKey(Integer id); 13 14 int updateByPrimaryKeySelective(Messgae record); 15 16 int updateByPrimaryKey(Messgae record); 17 }