将文档直接保存为Spring-data-Couchbase中的id值

问题描述 投票:1回答:1

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

@Document
public class SimplePojo{

    @Id
    private String id;

    @Field()
    private String complexJsonString;//the JSON string is stored in this variable
}

我还有一个SimplePojoRepository,如下所示

@Component
public interface SimplePojoRepository extends CouchbaseRepository<SimplePojo, String>{
}

现在,我在调用save方法之前手动设置id和complexJsonString: -

 SimplePojo myObj= new SimplePojo();
 myObj.setId(myKey);
 myObj.setComplexJsonString(jsonString);
 simplePojoRepository.save(myObj); 

这工作正常,但它以下面的格式保存文档

myKey: {
  complexJsonString : {//the original json Object here}
}

但我不想要这个,我想这样保存: -

myKey : {//the original json Object here}

所以,为了说清楚,我不想将我的JSON对象保存为complexJsonString的值,而是直接作为myKey的值。有人可以指导我如何实现这一目标吗?

couchbase spring-data-couchbase
1个回答
2
投票

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

myObj.setSomeEntity(new SomeEntity())

您可以使用jackson的ObjectMapper轻松地将JSON编码的String转换为对象:

ObjectMapper mapper = new ObjectMapper();
mapper.readValue( jsonString, SomeEntity.class);

但是,如果您无法控制此json的结构,则需要使用标准Java SDK而不是Spring Data One:

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)

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

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

例如:

SELECT
    i.itemName as itemName,
    SUM(i.quantity) AS totalQuantity
FROM sessionstore s
UNNEST DECODE_JSON(s.sessionCart).shoppingCart.items i
WHERE s.sessionCart IS NOT MISSING
GROUP BY i.itemName
ORDER BY SUM(i.quantity) DESC
LIMIT 10

© www.soinside.com 2019 - 2024. All rights reserved.