AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79566748
Accepted
PAMPA ROY
PAMPA ROY
Asked: 2025-04-10 21:14:32 +0800 CST2025-04-10 21:14:32 +0800 CST 2025-04-10 21:14:32 +0800 CST

Estamos migrando do Spring 2.xx (Hibernate 5) para o Spring 3.xx (Hibernate 6). O caso de teste está usando H2. Mas estamos enfrentando um problema de restrição de chave única.

  • 772

Classe de entidade

@Getter
@Setter
@NoArgsConstructor
@Entity
@ToString
@Table(name = "category_config")
public class CategoryConfig extends BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @NotNull(groups = Existing.class)
    @Null(groups = New.class)
    private Long categoryConfigId;

Classe de serviço

CategoryConfig pública addCategory(CategoryConfig

categoryConfig,String tenantId) {
    log.info(" info categoryConfig {} ", categoryConfig);
    if (categoryConfig == null||categoryConfig.getDeptNbr()==null) {
        throw new AllocationRuntimeException(ErrorCodes.CATEGORY_NUMBER_MANDATORY.getError());
    }
    categoryConfig.setTenantId(tenantId);
    categoryConfig.setAllocationStatus(ItemSetupAllocationStatus.PROGRESS.getValue());
    categoryConfig.setItemType(ItemType.INSEASON.getValue());
    try {
        return categoryConfigRepository.save(categoryConfig);
    } catch (Exception e) {
        throw new AllocationRuntimeException(e,
                ErrorCodes.CATEGORY_NUMBER_ALREADY_CONFIGURED.getError(categoryConfig.getDeptNbr()));
    }
}

configuração h2:

spring:
    cloud:
        gcp:
          core:
            enabled: false
          bigquery:
            datasetName: test
            project-id: test
            enabled: false
        azure:
           storage:
              blob:
                storage-url: https://test.blob.core.windows.net
    datasource:
        driver-class-name: org.h2.Driver
        url: jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE
        username:
        password:
    jpa:
        defer-datasource-initialization: true
        database-platform: org.hibernate.dialect.H2Dialect
        show-sql: true
        properties:
            hibernate:
                format_sql: true
                ddl-auto: update

Dados dentro de h2:

INSERT INTO category_config(category_config_id, dept_nbr, dept_desc, created_by, created_on, last_updated_by, last_updated_on, sum_need_qty_cdf, sum_need_qty_legacy, allocated_items, wk_supply, wk_supply_legacy, allocation_description, inherit_global_decile, isVLTRequired, tenant_id, allocation_status, item_type, current_doh) VALUES(1, 202, 'edit cat test', 's0k06wm', '2022-08-26', 's0k06wm', '2022-08-26', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'sams_us', 'Allocation available', 'inseason,preseason',7)
INSERT INTO category_config(category_config_id, dept_nbr, dept_desc, created_by, created_on, last_updated_by, last_updated_on, sum_need_qty_cdf, sum_need_qty_legacy, allocated_items, wk_supply, wk_supply_legacy, allocation_description, inherit_global_decile, isVLTRequired, tenant_id, allocation_status, item_type, current_doh) VALUES(2, 12, 'cat test 12', 's0k06wm', '2022-08-26', 's0k06wm', '2022-08-26', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'sams_mx', 'Allocation available', 'inseason',8)
INSERT INTO category_config(category_config_id, dept_nbr, dept_desc, created_by, created_on, last_updated_by, last_updated_on, sum_need_qty_cdf, sum_need_qty_legacy, allocated_items, wk_supply, wk_supply_legacy, allocation_description, inherit_global_decile, isVLTRequired, tenant_id, allocation_status, item_type, current_doh) VALUES(3, 14, 'cat test 14', 's0k06wm', '2022-08-26', 's0k06wm', '2022-08-26', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'sams_mx', 'Allocation available', 'inseason,preseason',8)
INSERT INTO category_config(category_config_id, dept_nbr, dept_desc, created_by, created_on, last_updated_by, last_updated_on, sum_need_qty_cdf, sum_need_qty_legacy, allocated_items, wk_supply, wk_supply_legacy, allocation_description, inherit_global_decile, isVLTRequired, tenant_id, allocation_status, item_type, current_doh) VALUES(4, 7, 'JUGUETES', 's0k06wm', '2022-08-26', 's0k06wm', '2022-08-26', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'sams_mx', 'Allocation available', 'inseason,preseason',8)
INSERT INTO category_config(category_config_id, dept_nbr, dept_desc, created_by, created_on, last_updated_by, last_updated_on, sum_need_qty_cdf, sum_need_qty_legacy, allocated_items, wk_supply, wk_supply_legacy, allocation_description, inherit_global_decile, isVLTRequired, tenant_id, allocation_status, item_type, current_doh) VALUES(5, 1990, 'edit cat test', 's0r0e4g', '2023-05-30', 's0r0e4g', '2023-05-30', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'sams_us', 'Allocation available', 'inseason',8)
INSERT INTO category_config(category_config_id, dept_nbr, dept_desc, created_by, created_on, last_updated_by, last_updated_on, sum_need_qty_cdf, sum_need_qty_legacy, allocated_items, wk_supply, wk_supply_legacy, allocation_description, inherit_global_decile, isVLTRequired, tenant_id, allocation_status, item_type, current_doh) VALUES(6, 5000, 'test cat', 's0k06wm', '2022-08-26', 's0k06wm', '2022-08-26', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'sams_mx', 'Allocation available', 'inseason,preseason',8)

Estava funcionando bem no Spring 2.xx, mas no Spring 3.xx estou conseguindo

could not execute statement [Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.CATEGORY_CONFIG(CATEGORY_CONFIG_ID) ( /* key:1 */ NULL, 7, NULL, 202, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, CAST(1 AS BIGINT), TIMESTAMP '2022-08-26 00:00:00', TIMESTAMP '2022-08-26 00:00:00', NULL, 'Allocation available', 's0k06wm', 'edit cat test', 'inseason,preseason', 's0k06wm', 'sams_us')"; SQL statement:
insert into category_config (allocated_items,allocation_description,allocation_status,created_by,created_on,current_doh,current_stock_pct,dept_desc,dept_nbr,inherit_global_decile,isvltrequired,item_type,last_updated_by,last_updated_on,margin_onhand,profit,sales_amt,sales_qty,sum_need_qty_cdf,sum_need_qty_legacy,tenant_id,total_oh_qty,wk_supply,wk_supply_legacy,category_config_id) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,default) [23505-224]] [insert into category_config (allocated_items,allocation_description,allocation_status,created_by,created_on,current_doh,current_stock_pct,dept_desc,dept_nbr,inherit_global_decile,isvltrequired,item_type,last_updated_by,last_updated_on,margin_onhand,profit,sales_amt,sales_qty,sum_need_qty_cdf,sum_need_qty_legacy,tenant_id,total_oh_qty,wk_supply,wk_supply_legacy,category_config_id) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,default)]; SQL [insert into category_config (allocated_items,allocation_description,allocation_status,created_by,created_on,current_doh,current_stock_pct,dept_desc,dept_nbr,inherit_global_decile,isvltrequired,item_type,last_updated_by,last_updated_on,margin_onhand,profit,sales_amt,sales_qty,sum_need_qty_cdf,sum_need_qty_legacy,tenant_id,total_oh_qty,wk_supply,wk_supply_legacy,category_config_id) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,default)]; constraint [PRIMARY KEY]

Usando h2 versão 2.2.224

Anteriormente, funcionava bem. Há algum problema no Hibernate 6 com GenerationType.IDENTITY? A propósito, estamos passando categoryConfigId como nulo ao chamar o método save. Além disso, não declarei nenhuma tabela de criação explícita em h2, pois isso não era necessário em versões anteriores.

spring-boot
  • 1 1 respostas
  • 25 Views

1 respostas

  • Voted
  1. Best Answer
    Evgenij Ryazanov
    2025-04-10T21:59:33+08:002025-04-10T21:59:33+08:00

    Geradores de colunas de identidade padrão não alteram seu valor base quando você insere uma linha com um valor explicitamente especificado. É por isso que o próximo valor gerado ainda é 1 e entra em conflito com a linha inserida anteriormente.

    Se você inseriu linhas com valores 1, 2, …, 6, você também precisa ajustar o gerador desta coluna:

    ALTER TABLE category_config ALTER COLUMN category_config_id RESTART WITH 7;
    
    • 0

relate perguntas

  • Testando com inicialização de mola oauth2

  • Codificação de resposta de inicialização de mola não está funcionando

  • Spring Boot 3 e Thymeleaf - objeto não renderizado no formulário

  • Deseja acessar o microsserviço usando o nome do microsserviço sem o número da porta usando o servidor eureka

  • spring kafka registerListenerContainer método startImmediately sinalizador verdadeiro ou falso?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve