为什么在使用mybatis generator时没有生成enableSelectByPrimaryKey

问题描述

当我用这个命令生成mybatis xml文件时:

java -jar mybatis-generator-core-1.3.4.jar -configfile generatorConfig.xml -overwrite

一切正常,但最终我发现用户映射器结果文件没有类型化 SelectByPrimaryKey 函数。这是我生成文件配置的一部分:

<table tableName="users"
               enableCountByExample="true"
               enableupdateByExample="true"
               enableDeleteByExample="true"
               enableSelectByExample="true"
               enableSelectByPrimaryKey="true"
               enableupdateByPrimaryKey="true"
               selectByPrimaryKeyQueryId="true"
               selectByExampleQueryId="true">
            <generatedKey column="ID" sqlStatement="JDBC" identity="true" />
        </table>

我的数据库是 Postgresql 13。我该怎么做才能修复它?这是我的用户表 DML:

CREATE TABLE public.users (
    id int8 NOT NULL GENERATED ALWAYS AS IDENTITY,nickname varchar NULL,avatar_url varchar NULL,phone varchar NOT NULL,updated_time int8 NOT NULL,created_time int8 NOT NULL,salt varchar NULL,pwd varchar NULL,sex int4 NULL,level_type varchar NULL,phone_region varchar NULL,country_code int4 NULL,user_status int4 NULL DEFAULT 1,last_login_time int8 NULL,first_login_time int8 NULL,app_id int4 NOT NULL,register_time int8 NULL,apple_iap_product_id varchar NULL,CONSTRAINT unique_phone UNIQUE (phone)
);

解决方法

您发布的 DML 显示该表没有主键。你有两个选择。

您可以通过将其添加到 create table 语句中来定义表中的主键:

create table public.users (
  ...
  primary key (id)
);

或者,如果不想在数据库中定义主键,可以使用MyBatis Generator中的“VirtualPrimaryKeyPlugin”。请参阅此处了解详情:https://mybatis.org/generator/reference/plugins.html