mybatis-generator-maven-plugin插件的一些坑

1、配置mybatis-generator-maven-plugin插件

在maven的pom.xml的<build></build>节点内添加 

<!--要放在与pluginManagement同级别才能生效-->

<plugins>

  <plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.5</version>
    <configuration>
      <verbose>true</verbose>
      <overwrite>false</overwrite>
    </configuration>
  </plugin>
 
</plugins>

 代码段中标红的部分不写的话,每次自动生成后会出现以数字后缀的备份文件 如图

配置好maven自动下载,一定要注意把xml代码段放到与pluginManagement同级别,idea下的maven插件里才能出来

安装完成后,idea右侧的maven插件里就有了如下图:

2、配置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 
 6 <generatorConfiguration>
 7 
 8     <!--导入属性配置-->
 9     <properties resource="jdbc.properties"></properties>
10     <classPathEntry location="${jdbc.jar}"/>
11 
12     <context id="DB2Tables" targetRuntime="MyBatis3">
13        
14         <!-- 生成注释为false 不生成为true 【不生成注释时会被重复写入导致报错】 -->
15         <commentGenerator>
16             <property name="suppressAllComments" value="false"/>
17         </commentGenerator>
18 
19         <!--jdbc的数据库连接 -->
20         <jdbcConnection
21                 driverClass="${jdbc.Driverclass}"
22                 connectionURL="${jdbc.jdbcurl}"
23                 userId="${jdbc.user}"
24                 password="${jdbc.password}">
25         </jdbcConnection>
26 
27         <javaTypeResolver >
28             <property name="forceBigDecimals" value="false" />
29         </javaTypeResolver>
30 
31         <!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
32             targetPackage     指定生成的model生成所在的包名
33             targetProject     指定在该项目下所在的路径
34         -->
35         <!--<javaModelGenerator targetPackage="com.mmall.pojo" targetProject=".\src\main\java">-->
36         <javaModelGenerator targetPackage="com.*.pojo" targetProject="./src/main/java">
37             <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
38             <property name="enableSubPackages" value="false"/>
39             <!-- 是否对model添加 构造函数 -->
40             <property name="constructorBased" value="true"/>
41             <!-- 是否对类CHAR类型的列的数据进行trim操作 -->
42             <property name="trimStrings" value="true"/>
43             <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
44             <property name="immutable" value="false"/>
45         </javaModelGenerator>
46 
47         <!--mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
48         <sqlMapGenerator targetPackage="mappers" targetProject="./src/main/resources">
49             <property name="enableSubPackages" value="false"/>
50         </sqlMapGenerator>
51 
52         <!-- targetPackage:mapper接口dao生成的位置 -->
53         <javaClientGenerator type="XMLMAPPER" targetPackage="com.*.dao" targetProject="./src/main/java">
54             <!-- enableSubPackages:是否让schema作为包的后缀 -->
55             <property name="enableSubPackages" value="false" />
56         </javaClientGenerator>
57 
58 
59         <table tableName="admin" domainObjectName="Admin" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
60             <property name="rootInterface" value="com.*.dao.AdminExtMapper"/>
61         </table>
62         <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
63 
64 
65     </context>
66 </generatorConfiguration>
http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd  这条报红 不用管

 <!-- 生成注释为false 不生成为true 【不生成注释时会被重复写入导致报错】 -->
      <commentGenerator>
            <property name="suppressAllComments" value="false"/>
      </commentGenerator>
加上注释后,每次生成xml和生成的实体类不会被覆盖,不加注释的话 xml会被重复写入,导致程序报错。

3、数据库字段更新问题

当后期数据库的字段新增或者修改后,重新执行插件,会发现DAO层下自己辛辛苦苦写的方法代码被覆盖了,只能使用先备份再生成然后再手工修改xml文件和mapper文件。这样太麻烦了。

查了下官方文档,我试着用父接口的形式来实现。

以admin数据表为例

CREATE TABLE `admin` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

  

generatorConfig.xml 文件下修改  让AdminMapper 接口继承一个AdminExtMapper的父接口

 <table tableName="admin" domainObjectName="Admin" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
            <property name="rootInterface" value="com.*.dao.AdminExtMapper"/>
        </table>

点击自动生成了 AdminMapper、AdminMapper.xml 和 Admin类

package com.*.dao;

import com.*.pojo.Admin;

public interface AdminMapper extends AdminExtMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table admin
     *
     * @mbg.generated Tue Apr 09 17:24:16 CST 2019
     */
    int deleteByPrimaryKey(Integer id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table admin
     *
     * @mbg.generated Tue Apr 09 17:24:16 CST 2019
     */
    int insert(Admin record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table admin
     *
     * @mbg.generated Tue Apr 09 17:24:16 CST 2019
     */
    int insertSelective(Admin record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table admin
     *
     * @mbg.generated Tue Apr 09 17:24:16 CST 2019
     */
    Admin selectByPrimaryKey(Integer id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table admin
     *
     * @mbg.generated Tue Apr 09 17:24:16 CST 2019
     */
    int updateByPrimaryKeySelective(Admin record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table admin
     *
     * @mbg.generated Tue Apr 09 17:24:16 CST 2019
     */
    int updateByPrimaryKey(Admin record);
}

在DAO层 写一个 AdminExtMapper 父接口 放入自己写的方法

public interface AdminExtMapper {

    int SelectBy(String username);

    Admin findAdmin(@Param("username") String username, @Param("password") String password);
}
在mapper文件夹下创建AdminExtMapper.xml 把AdminMapper.xml下的代码复制过来,精简一下,加上自己的sql语句
<?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.imcdn.dao.AdminExtMapper">
    <resultMap id="BaseResultMap" type="com.*.pojo.Admin">
        <constructor>
            <idArg column="id" javaType="java.lang.Integer" jdbcType="INTEGER"/>
            <arg column="username" javaType="java.lang.String" jdbcType="VARCHAR"/>
            <arg column="password" javaType="java.lang.String" jdbcType="VARCHAR"/>
        </constructor>
    </resultMap>
    <sql id="Base_Column_List">
    id, username, password
  </sql>
    <select id="SelectBy" parameterType="string" resultType="int">
        select count(id) from admin where username=#{username}
    </select>

    <select id="findAdmin" parameterType="map" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from admin where username=#{username} and password=#{password}
    </select>

</mapper>
 

这样的话 当修改字段后 再次生成时就不用重复改代码了。

测试

AdminServiceImpl 

@Service("iAdminService")
public class AdminServiceImpl implements IAdminSevice {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public ServerResponse<Admin> login(String username, String password) {
        int i = adminMapper.SelectBy(username);
        if(i==0){
            return ServerResponse.createByErrorMsg("该用户名不存在");
        }

        String md5Password= MD5Util.MD5EncodeUtf8(password);
        Admin admin = adminMapper.findAdmin(username, md5Password);
        if(admin==null){
            return  ServerResponse.createByErrorMsg("用户密码不匹配");
        }
        return  ServerResponse.createBySuccess("登陆成功",admin);
    }
}

AdminController

Controller
@RequestMapping("/admin/")
public class AdminController {

    @Autowired
    private IAdminSevice iAdminSevice;

    @RequestMapping(value = "login.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<Admin> login(String usename, String password, HttpSession session) {
        ServerResponse<Admin> response = iAdminSevice.login(usename, password);
        if (response.isSuccess()) {
            session.setAttribute(Const.CURRENT_USER, response.getData());
        }
        return response;
    }
}

测试结果





猜你喜欢

转载自www.cnblogs.com/yanglaoxie/p/10678570.html