mybatis-generator自动生成代码

来源:互联网 发布:minecraft java 编辑:程序博客网 时间:2024/04/30 14:43

1.场景分析

   在实际项目中,很多寻常的逻辑,例如:数据库表的增,删,改,查;这些徒手写确实有些费人力又费时间,今天笔者向大家介绍自动生成代码的插件:mybatis-generator

2.实现步骤

①在pom.xml中配置generator插件

<build>    <plugins>        <!-- Package the project as an executable jar -->        <plugin>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-maven-plugin</artifactId>            <!-- Set the character encoding for the JVM -->            <configuration>                <jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>            </configuration>        </plugin>        <!--代码生成-->        <plugin>            <groupId>org.mybatis.generator</groupId>            <artifactId>mybatis-generator-maven-plugin</artifactId>            <version>1.3.5</version>            <dependencies>                <dependency>                    <groupId> mysql</groupId>                    <artifactId> mysql-connector-java</artifactId>                    <version> ${mysql-connector-java.version}</version>                </dependency>                <dependency>                    <groupId>org.mybatis.generator</groupId>                    <artifactId>mybatis-generator-core</artifactId>                    <version>1.3.5</version>                </dependency>            </dependencies>            <executions>                <execution>                    <id>Generate MyBatis Artifacts</id>                    <phase>package</phase>                    <goals>                        <goal>generate</goal>                    </goals>                </execution>            </executions>            <configuration>                <!--允许移动生成的文件 -->                <verbose>true</verbose>                <!-- 是否覆盖 -->                <overwrite>true</overwrite>                <!-- 自动生成的配置 -->                <configurationFile>                    src/main/resources/mybatis-generator.xml</configurationFile>            </configuration>        </plugin>    </plugins></build>

②在src/main/resources下创建mybatis-generator.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"><generatorConfiguration>    <context id="DB2Tables"    targetRuntime="MyBatis3">        <commentGenerator>            <property name="suppressDate" value="true"/>            <property name="suppressAllComments" value="true"/>        </commentGenerator>        <!--数据库链接地址账号密码-->        <jdbcConnection driverClass="com.mysql.jdbc.Driver"                         connectionURL="jdbc:mysql://127.0.0.1:3306/permission" userId="root" password="root">        </jdbcConnection>        <javaTypeResolver>            <property name="forceBigDecimals" value="false"/>        </javaTypeResolver>        <!--生成Model类存放位置-->        <javaModelGenerator targetPackage="com.zhangxing.model" targetProject="src/main/java">            <property name="enableSubPackages" value="true"/>            <property name="trimStrings" value="true"/>        </javaModelGenerator>        <!--生成映射文件存放位置-->        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">            <property name="enableSubPackages" value="true"/>        </sqlMapGenerator>        <!--生成Dao类存放位置-->        <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码                type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象                type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象                type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口        -->        <javaClientGenerator type="XMLMAPPER" targetPackage="com.zhangxing.dao" targetProject="src/main/java">            <property name="enableSubPackages" value="true"/>        </javaClientGenerator>        <!--生成对应表及类名-->        <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>        <table tableName="role" domainObjectName="Role" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>        <table tableName="permission" domainObjectName="Permission" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>        <table tableName="user_role" domainObjectName="UserRole" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>        <table tableName="role_permission" domainObjectName="RolePermission" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>    </context></generatorConfiguration>
自动创建的表来源

<jdbcConnection driverClass="com.mysql.jdbc.Driver"          connectionURL="jdbc:mysql://127.0.0.1:3306/permission" userId="root" password="root"></jdbcConnection>
自动创建的model目录

<javaModelGenerator targetPackage="com.zhangxing.model" targetProject="src/main/java">            <property name="enableSubPackages" value="true"/>            <property name="trimStrings" value="true"/></javaModelGenerator>
自动创建的dao目录

<javaClientGenerator type="XMLMAPPER" targetPackage="com.zhangxing.dao" targetProject="src/main/java">            <property name="enableSubPackages" value="true"/></javaClientGenerator>
自动创建的mapper映射目录

 <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">            <property name="enableSubPackages" value="true"/> </sqlMapGenerator>
去除自动生成代码的注解(代码生成时间及dao层的所有注解)

<commentGenerator>     <property name="suppressDate" value="true"/>     <property name="suppressAllComments" value="true"/></commentGenerator>

申明数据库对应表名及对应的model名称

tableName="role_permission" domainObjectName="RolePermission"

自动生成代码样式的选择

<javaClientGenerator type="XMLMAPPER" targetPackage="com.zhangxing.dao" targetProject="src/main/java">            <property name="enableSubPackages" value="true"/>        </javaClientGenerator>
其中type可以有以下选择可供参考

<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码                type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象                type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象                type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口  -->
有兴趣的伙伴可以逐一实践下效果;

③application.properities配置

# EMBEDDED SERVER CONFIGURATION (ServerProperties)server.port=8089server.session-timeout=1800server.context-path=server.tomcat.max-threads=0server.tomcat.uri-encoding=UTF-8server.tomcat.basedir=target/tomcat# HTTP encoding (HttpEncodingProperties)spring.http.encoding.charset=UTF-8spring.http.encoding.enabled=true spring.http.encoding.force=true#datasourcespring.datasource.url=jdbc:mysql://localhost/permission?useUnicode=true&characterEncoding=UTF-8spring.datasource.username=rootspring.datasource.password=rootspring.datasource.driverClassName=com.mysql.jdbc.Driver#mybatismybatis.type-aliases-package=com.zhangxing.modelmybatis.mapper-locations=classpath:mapper/*.xml#mappermapper.mappers=tk.mybatis.mapper.common.Mappermapper.not-empty=falsemapper.identity=MYSQL#pagehelperpagehelper.helperDialect=mysqlpagehelper.reasonable=truepagehelper.supportMethodsArguments=truepagehelper.params=count=countSql#logging#logging.level.root=INFO#logging.level.org.springframework.web=DEBUGlogging.level.org.zhangxing=DEBUGspring.velocity.suffix=.html
主要是mybatis实体类及映射mapper扫描

#mybatismybatis.type-aliases-package=com.zhangxing.modelmybatis.mapper-locations=classpath:mapper/*.xml
④Application启动类

@SpringBootApplication@MapperScan(basePackages = "com.zhangxing.dao")public class Application extends SpringBootServletInitializer{    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }}
dao层接口的扫描

@MapperScan(basePackages = "com.zhangxing.dao")
⑤然后点击Run-->Edit Configrations


⑥接着点击绿色的“+”号,选择Maven


⑦在界面的command line中添加命令

mybatis-generator:generate -e

⑧点击ok,执行配好的generator-auto


ok,执行效果如下


3.效果展示

①自动生成的映射mapper(以user为例)


②自动生成的model


③自动生成的dao


补充:dao层分析

package com.zhangxing.dao;import com.zhangxing.model.User;public interface UserMapper {    int deleteByPrimaryKey(Integer id);    int insert(User record);    int insertSelective(User record);    User selectByPrimaryKey(Integer id);    int updateByPrimaryKeySelective(User record);    int updateByPrimaryKey(User record);}
在dao层没有自动生成任何注解,也无需加注解;因为在Application启动类中,我们已经扫描了dao层的所有接口

测试类

@RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = Application.class)public class ServiceTest {    @Autowired    private UserService userMapper;    @Test    public void test(){        User user = userMapper.selectByPrimaryKey(1);        System.out.println(user.getName());    }}

运行结果:


好了,自动生成代码就搞定了,这样可以节省大量的基础开发时间了;我是张星,欢迎加入 博主技术交流群,群号:313145288

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 奶茶店电脑下单怎么办 个体户营业执照注销怎么办清税业务 注册公司没有办公地点怎么办 变更莒业执照法人怎么办手续 欠了几十万贷款怎么办 杭州公司跨区迁址怎么办 公司同市内跨区迁址怎么办 合同写错了字怎么办 农行卡转工行卡怎么办 外地人在北京交社保退休怎么办 身份证掉了单位宿舍怎么办居住证 广州租住单位宿舍怎么办居住证 公司u盾丢了怎么办 北京办了居住卡怎么办延期 商铺被陌生人注册左公司怎么办 营业执照年检登录密码忘了怎么办 欠人家钱没钱还怎么办 欠钱实在没钱还怎么办 党关系丢了10年怎么办? 离婚后生孩子怎么办出生证明 注册公司没有注册地址怎么办 银行流水不够2倍怎么办 个体户小店怎么办五险 姓和名五行相克怎么办? 三星s7刷机后计算器没有了怎么办 线雕鼻子山根鼓怎么办 在日本没有日币怎么办 明知合同回扣特别高怎么办 医院药品断货了怎么办 空腹吃菠萝胃疼怎么办 小孩黑户口怎么办上户 别人说名字起大了怎么办? 念佛号时心老是不集中怎么办 扑lv期嗓子痛头痛怎么办 公众号忘记了账号怎么办 公众号账号密码忘记了怎么办 现实生活被小人缠上怎么办 五行缺木和水怎么办 八字火旺的人怎么办 综合旺衰得分负怎么办 妈妈误打死一只黄鼠狼怎么办