Couchbase 在Spring数据库中将文档直接保存为id值

Couchbase 在Spring数据库中将文档直接保存为id值,couchbase,spring-data-couchbase,Couchbase,Spring Data Couchbase,我想在Couchbase中将JSON对象保存为文档。此文档的id应该从这个JSON对象中检索,而值应该是这个JSON对象本身。由于这个JSON太复杂,我没有直接将它映射到任何POJO类,但我创建了一个简单的POJO,它有两个字段,如下所示 @Document public class SimplePojo{ @Id private String id; @Field() private String complexJsonString;//the JSON s

我想在Couchbase中将JSON对象保存为文档。此文档的id应该从这个JSON对象中检索,而值应该是这个JSON对象本身。由于这个JSON太复杂,我没有直接将它映射到任何POJO类,但我创建了一个简单的POJO,它有两个字段,如下所示

@Document
public class SimplePojo{

    @Id
    private String id;

    @Field()
    private String complexJsonString;//the JSON string is stored in this variable
}
@Component
public interface SimplePojoRepository extends CouchbaseRepository<SimplePojo, String>{
}
我还有一个SimplePojoRepository,如下所示

@Document
public class SimplePojo{

    @Id
    private String id;

    @Field()
    private String complexJsonString;//the JSON string is stored in this variable
}
@Component
public interface SimplePojoRepository extends CouchbaseRepository<SimplePojo, String>{
}
这工作正常,但它正在以以下格式保存文档

myKey: {
  complexJsonString : {//the original json Object here}
}
但我不想这样,我想这样保存它:-

myKey : {//the original json Object here}

因此,为了明确起见,我不想将我的JSON对象保存为
complexJsonString
的值,而是直接保存为
myKey
的值,请有人指导我如何实现这一点吗?

如果要将complexJsonString作为嵌套实体存储在主对象中,您必须在Pojo中对其进行转换:

myObj.setSomeEntity(new SomeEntity())
您可以使用jackson的ObjectMapper轻松地将JSON编码字符串转换为对象:

ObjectMapper mapper = new ObjectMapper();
mapper.readValue( jsonString, SomeEntity.class);
但是,如果您无法控制此json的结构,则需要使用标准Java SDK而不是Spring Data SDK:

JsonObject obj = JsonObject.create().put(this.documentTypeName, this.documentValue)
                    .put("attrNam1", "attrValue1")
                    .put("attrNam2", "attrValue2")

JsonDocument doc = JsonDocument.create(session.getId(), maxExpirationTime, obj);
bucket.upsert(doc)

在上面的例子中,您需要使用一些库(例如:gson/jackson)解析JSON编码的字符串,然后将其转换为couchbase JsonDocument

最后,您还可以保持代码原样,并在需要访问此JSON字符串的某些属性时使用N1QL函数
DECODE_JSON()

例: