{"record":{"id":"445e9c367f3b9fc7","repo":"elunez/eladmin","slug":"classname-with-column-columnname-existed","errorCode":null,"errorMessage":"${className} with ${column.columnName} {} existed","messagePattern":"(.+?) with (.+?) (.+?) existed","errorType":"exception","errorClass":"EntityExistException","httpStatus":400,"severity":"warning","filePath":"eladmin-generator/src/main/resources/template/admin/ServiceImpl.ftl","lineNumber":103,"sourceCode":"        ValidationUtil.isNull(${changeClassName}.get${pkCapitalColName}(),\"${className}\",\"${pkChangeColName}\",${pkChangeColName});\n        return ${changeClassName}Mapper.toDto(${changeClassName});\n    }\n\n    @Override\n    @Transactional(rollbackFor = Exception.class)\n    public void create(${className} resources) {\n<#if !auto && pkColumnType = 'Long'>\n        Snowflake snowflake = IdUtil.createSnowflake(1, 1);\n        resources.set${pkCapitalColName}(snowflake.nextId()); \n</#if>\n<#if !auto && pkColumnType = 'String'>\n        resources.set${pkCapitalColName}(IdUtil.simpleUUID()); \n</#if>\n<#if columns??>\n    <#list columns as column>\n    <#if column.columnKey = 'UNI'>\n        if(${changeClassName}Repository.findBy${column.capitalColumnName}(resources.get${column.capitalColumnName}()) != null){\n            throw new EntityExistException(${className}.class,\"${column.columnName}\",resources.get${column.capitalColumnName}());\n        }\n    </#if>\n    </#list>\n</#if>\n        ${changeClassName}Repository.save(resources);\n    }\n\n    @Override\n    @Transactional(rollbackFor = Exception.class)\n    public void update(${className} resources) {\n        ${className} ${changeClassName} = ${changeClassName}Repository.findById(resources.get${pkCapitalColName}()).orElseGet(${className}::new);\n        ValidationUtil.isNull( ${changeClassName}.get${pkCapitalColName}(),\"${className}\",\"id\",resources.get${pkCapitalColName}());\n<#if columns??>\n    <#list columns as column>\n        <#if column.columnKey = 'UNI'>\n        <#if column_index = 1>\n        ${className} ${changeClassName}1 = null;\n        </#if>","sourceCodeStart":85,"sourceCodeEnd":121,"githubUrl":"https://github.com/elunez/eladmin/blob/55fbf705956949697dbd68bf9003776609d3d029/eladmin-generator/src/main/resources/template/admin/ServiceImpl.ftl#L85-L121","documentation":"Not a runtime throw but a FreeMarker template line in the code generator (ServiceImpl.ftl): for every column flagged UNIQUE in the inspected table, the generated service's create() calls `repository.findBy<Column>(...) != null` and throws EntityExistException(\"${className} with ${column.columnName} {} existed\", value). At generation time the placeholders ${className}/${column.columnName} are filled; at runtime of the GENERATED code this fires when inserting a row whose unique column value already exists.","triggerScenarios":"Generating a module from a table with one or more UNIQUE-key columns, then calling the generated POST create endpoint with a value for that column that is already stored — e.g. creating a user with an existing username, a dict with an existing name.","commonSituations":"Duplicate submissions in the generated admin UI; import scripts colliding with existing rows; race conditions where two concurrent creates pass the findBy check and the DB unique constraint then throws a DataIntegrityViolationException instead; tables whose unique index is composite (this template only guards single-column UNI).","solutions":["Submit a value not yet present for the unique column (check via the generated list/query endpoint first).","If duplicates keep occurring from double clicks, debounce/disable the submit button until the response.","For concurrent creates, rely on/also handle the DB unique constraint (catch DataIntegrityViolationException) since the findBy-then-save check is not atomic.","Adjust the .ftl template to generate an upsert or a friendlier message if you control the generator templates.","Regenerate the module after changing the table's unique keys so the guards match reality."],"exampleFix":"// before (generated code pattern)\nif(userRepository.findByUsername(resources.getUsername()) != null){\n    throw new EntityExistException(User.class, \"username\", resources.getUsername());\n}\nuserRepository.save(resources);\n\n// after: also handle the race via the DB constraint\ntry {\n    userRepository.save(resources);\n} catch (DataIntegrityViolationException e) {\n    throw new EntityExistException(User.class, \"username\", resources.getUsername());\n}","handlingStrategy":"validation","validationCode":"// pre-check uniqueness through the generated query API\nboolean taken = client.getByUsername(dto.getUsername()) != null;\nif (taken) { toast('用户名已存在'); return; }","typeGuard":null,"tryCatchPattern":"try { create(dto); } catch (EntityExistException e) { // e.getMessage() contains \"with username ... existed\": show duplicate-field error on that input } catch (DataIntegrityViolationException e) { // race lost to the DB constraint: same user-facing message }","preventionTips":["Disable submit buttons during in-flight creates to stop double submits.","Remember the findBy check is not atomic — unique DB constraints remain the real guarantee.","Regenerate modules after altering unique keys so guards match the schema."],"tags":["code-generator","freemarker","unique-constraint","duplicate","template"],"backgroundTag":null,"analyzedSha":"55fbf705956949697dbd68bf9003776609d3d029","analyzedAt":"2026-08-14T11:56:12.758Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}