【问题标题】:How to mapping postgresql jsonb to java object r2dbc如何将 postgresql jsonb 映射到 java 对象 r2dbc
【发布时间】:2021-03-23 03:25:24
【问题描述】:

我在 postgreSql 中有一个与表 pc_customer 的实体映射。 在使用 R2DBC 将字段 jsonb 从 postgreSql 映射到 Java 中的 Object 时出现问题。这是我的代码:

@EqualsAndHashCode(callSuper = false)
@Data
@Builder
@AllArgsConstructor(access = AccessLevel.PROTECTED)
@Table("pc_customer")
public class Customer extends KunlunDomain {
    @Id
    private Long id;
    private String secret;
    private String code;

    @Column(value = "customer_authorities")
    CustomerAuthorities customerAuthorities;
    String zaloId;

    @Data
    @Builder
    @AllArgsConstructor(access = AccessLevel.PROTECTED)
    public static class CustomerAuthorities implements Serializable {
        boolean importParcel = false;
        boolean printParcelStamp = false;
        boolean draftServicesEnable = true;
    }
}

这是我收到的错误 **引起:org.springframework.core.convert.ConverterNotFoundException:找不到能够从类型 [io.r2dbc.postgresql.codec.Json$JsonByteArrayInput] 转换为类型 [*com.example.Customer$CustomerAuthorities ]

列 customer_authorities 是 jsonb。 那么在这种情况下我能做些什么来将 jsonb 映射到一个类呢? 对不起我的英语

【问题讨论】:

    标签: java spring r2dbc


    【解决方案1】:

    创建 BiFunctional Row Mapper 用于将 DB 行映射到 java 对象 [On Repository]

    示例 -

    @Autowired
    private DatabaseClient databaseClient;
    
    @Autowired
    private ObjectMapper objectMapper
    public static final BiFunction<Row, RowMetadata, Customer> customerRowMapper = (row, rowMetadata) -> Customer.builder()
              // ...rest of the field
              // call your setter fun here 
              .customerAuthorities(objectMapper.readValue(row.get("customer_authorities", String.class), Customer.CustomerAuthorities.class))
              .build();
    
    public Flux<Customer> getAllCustomer() {
      return databaseClient
                .sql("YOUR SQL QUERY")
                .map(customerRowMapper) // here will call the biFunctional row mapper
                .all();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-14
      • 1970-01-01
      • 2012-07-18
      • 2020-01-16
      • 2014-11-02
      • 2021-12-08
      • 2013-04-17
      • 1970-01-01
      相关资源
      最近更新 更多