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 / user-21970245

PAMPA ROY's questions

Martin Hope
PAMPA ROY
Asked: 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.

  • 5

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 respostas
  • 25 Views
Martin Hope
PAMPA ROY
Asked: 2025-02-05 22:09:04 +0800 CST

JPQL não consegue reconhecer coluna

  • 5

Entidade:

@Getter
@Setter
@NoArgsConstructor
@Entity
@ToString
@DynamicUpdate
@Table(name = "flow_plan_details")
public class FlowPlanDetails extends BaseEntity{
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @NotNull(groups = Existing.class)
    @Null(groups = New.class)
    private Long flowPlanId;
    
    private Integer itemNbr;
    private String itemDescription;
    private String season;
    private Integer fiscalYear;
    private String catDesc;
    private String subcatDesc;
    private String gmm;
    private String dmm;
    private String planStatus;
    private String channel;
    
    private Boolean isLcl;
    private String imageUrl;
    private Integer carryOverItemNbr;
    private Integer palletQty;
    private Integer totalContQty;
    private Integer commitmentQty;
    private Integer defaultPresentation;
    private LocalDate inClubDate;
    private LocalDate oosDate;
    private String eventCode;
    private Integer clubCount;
    private Integer percContainerRoundUp;
    private String portOfOrigin;
    private String productId;
    
    
    private String flowRounding;
    private String breakdownCalculation;
    private Integer wos;
    private Integer lastWeekToReceive;
    private String targetOhRule;
    
    
    private Float itemCost;
    private Float itemRetail;
    private Float shippingCostPerPallet;
    private Float shippingCostPerContainer;
    private Float profitPerItem;
    private Float lostSale;
    private Float containerShippingCost;
    private Float totalCost;
    
    
    private String holidayName;
    private LocalDate holidayStartDate;
    private LocalDate holidayEndDate;
    private LocalDate holidayDate;
    private String applyHoliday;
    
    
    private Float plannedContainers;
    private Float plannedPallets;
    private Float flowContainers;
    private Float flowPallets;
    private Float differenceInContainers;
    private Float differenceInPallets;

    private LocalDateTime lastGeneratedFlowPlan;
    private Long rolloutId;
    private Boolean isRolloutRefreshRequired;
    private Boolean isArchived = false;

    private Float weight;
    private Float dimension1;
    private Float dimension2;
    private Float dimension3;
    private Boolean sorted;

    private String impactDropdown;
    private Boolean isReadyForScgs;
    private String finalizedStatus;
    
    public interface Existing {
    }

    public interface New {
    }

    public String getFlowplanIdWithName()
    {
        return this.getFlowPlanId().toString()+" - "+this.getItemDescription()+" - "+ this.getChannel();
    }
}

Estou executando esta consulta:

@Query("""
       select f from FlowPlanDetails f
       where f.last_updated_on between :startDate and :endDate
       and f.plan_status=:planStatus and f.is_archived=:isArchived
       and f.cat_desc= :catDesc
       """) //(:catDesc is NULL OR f.cat_desc= :catDesc)
Page<FlowPlanDetails> customSpotQuery(@Param("catDesc") String catDesc,
        @Param("startDate") ZonedDateTime startDate,
        @Param("endDate") ZonedDateTime endDate,
        @Param("planStatus") String planStatus,
        @Param("isArchived") Boolean isArchived, Pageable page);

Estou recebendo este erro:

Causado por: java.lang.IllegalArgumentException: org.hibernate.QueryException: não foi possível resolver a propriedade: last_updated_on de: com.walmart.sams.services.allocation.configuration.service.model.FlowPlanDetails [selecione f de com.walmart.sams.services.allocation.configuration.service.model.FlowPlanDetails f onde f.last_updated_on entre :startDate e :endDate e f.plan_status=:planStatus e f.is_archived=:isArchived e f.cat_desc= :catDesc]

Agora a coluna last_updated_on vem de BaseEntity. Como resolver isso?

spring-boot
  • 1 respostas
  • 16 Views
Martin Hope
PAMPA ROY
Asked: 2024-11-11 01:31:32 +0800 CST

Python - SyntaxError: o nome 'point_to_managedDB' é atribuído antes da declaração global

  • 5
point_to_managedDB = None

def _get_correct_DB_flag():
    if ENV == "dev":
        global point_to_managedDB
        point_to_managedDB = os.environ.get("OIA_POINT_TO_MANAGED_DB_DEV")
    elif ENV == "stg":
        global point_to_managedDB
        point_to_managedDB = os.environ.get("OIA_POINT_TO_MANAGED_DB_STG")
    elif ENV == "prod":
        global point_to_managedDB
        point_to_managedDB = os.environ.get("OIA_POINT_TO_MANAGED_DB_PROD")

_get_correct_DB_flag()

O que há de errado neste código? Estou recebendo:

   File "/oia_application/scripts/database/env/sql_environments.py",
 line 37
     global point_to_managedDB
     ^ 
     SyntaxError: name 'point_to_managedDB' is assigned to before global declaration

Eu sei que há problemas semelhantes no SO, mas o que há de errado no meu código, não consigo descobrir. Declarei global somente dentro do método.

python
  • 1 respostas
  • 19 Views

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