首页 > 解决方案 > Couchbase - Auto generate key with user defined suffix

问题描述

I want to save an employee object in couchbase using spring boot java. I am using reactive couchbase driver. My requirement is to save the employee object with employeeId suffixed with hard coded string "-EMPLOYEETYPE".

Example: Object to couchbase from Java Application:

{ "employeeId" : "12345", "lname" :"ltest", "fname" : "ftest"}

While saving to couch base, key supposed to be generated like

"12345-EMPLOYEETYPE"

Below code is not working, kindly guide me how to achieve it. Note: I am using lombok so there are no getters and setters.

@Document
public final class Employee {

        @Id @GeneratedValue(strategy = GenerationStrategy.USE_ATTRIBUTES,delimiter="-EMPLOYEETYPE")
        private String id;

        @IdAttribute
        private String employeeId;
}

标签: javaspring-bootcouchbasespring-webflux

解决方案


找到了解决方案。我们需要创建一个实例变量,并为其分配后缀字符串文字,并使用@IdSuffix 进行注释。(对于前缀,@IdPrefix)。该字段不会持久化到 couchbase 中,仅用于生成文档的 id。

@Document
public final class Employee {

    @Id @GeneratedValue(strategy = GenerationStrategy.USE_ATTRIBUTES,delimiter="-")
    private String id;

    @IdAttribute
    private String employeeId;

    @IdSuffix
    private String suffix = "EMPLOYEETYPE";
}

参考文档:https ://docs.spring.io/spring-data/couchbase/docs/current/reference/html/#couchbase.autokeygeneration.configuration


推荐阅读