DEV Community

Edgar Rios Navarro
Edgar Rios Navarro

Posted on

3 1

Manejar PK Compuesta con Spring-R2DBC

Hasta la versión spring-data-r2dbc:1.3.2 no es posible usar Composite Key para mapear una tabla con más de un campo como PK.

Como workaround se tiene este ejemplo.


La tabla en la base de datos Postgresql, se muestra con una PK compuesta:

alt text

alt text

Vamos a agregar un campo que simule ser un PK. Debe ser del tipo autoincrement.

alter table public.order_line
add column id serial not null unique;
Enter fullscreen mode Exit fullscreen mode

alt text


Por parte del código Java, en el objeto que mapeamos dicha tabla; le especificamos como Id el nuevo campo.

@Table("order_line")
public class OrderLineDTO {

    @Id
    Long id;
    //PK
    String orderLineNumber;
    //PK
    Long orderNumber;
    @CreatedDate
    private LocalDateTime createdAt;
    @LastModifiedDate
    private LocalDateTime updatedAt;
Enter fullscreen mode Exit fullscreen mode

Lo siguiente será implementar las búsquedas por los campos que conforman la llave primaria real.

@Repository
public interface OrderLineSpringRepository extends ReactiveCrudRepository<OrderLineDTO, Long> {
Mono<OrderLineDTO> findByOrderNumberAndOrderLineNumber(Long orderNumber, String orderLineNumber);
Mono<Boolean> existsByOrderNumberAndOrderLineNumber(Long orderNumber, String orderLineNumber);
}

Documentación

https://www.postgresqltutorial.com/postgresql-serial/
https://docs.spring.io/spring-data/r2dbc/docs/1.3.2/reference/html/#r2dbc.repositories

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay