Marklogic - 在Java api中插入pojo作为json文档
问题描述:
我想在使用java api的marklogic中插入pojo对象作为json文档。我使用this作为插入pojo作为xml文档的参考。Marklogic - 在Java api中插入pojo作为json文档
我无法注册我的pojo类与JSON句柄。
public class JSONDocument {
public static void main(String[] args) throws JAXBException, IOException {
run(Util.loadProperties());
}
@JsonRootName(value = "product")
static public class Product {
@JsonProperty
private String name;
@JsonProperty
private String industry;
@JsonProperty
private String description;
public Product() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIndustry() {
return industry;
}
public void setIndustry(String industry) {
this.industry = industry;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
public static void run(ExampleProperties props) throws JAXBException {
runShortcut(props);
System.out.println("Wrote, read, and deleted "+Product.class.getName()+" using JAXB");
}
public static void runShortcut(ExampleProperties props) throws JAXBException {
// register the POJO classes like JAXB - JAXBHandle.newFactory(Product.class)
DatabaseClientFactory.getHandleRegistry().register(
// Need help here for - registering pojo for JSON
);
// create the client
DatabaseClient client = DatabaseClientFactory.newClient(
props.host, props.port, props.writerUser, props.writerPassword,
props.authType);
// create a manager for JSON documents
JSONDocumentManager docMgr = client.newJSONDocumentManager();
// create an instance of the POJO class
Product product = new Product();
product.setName("FashionForward");
product.setIndustry("Retail");
product.setDescription(
"(Shortcut) Creates demand with high prices, hours from midnight to dawn, and frequent moves");
// create an identifier for the document
String docId = "/example/"+product.getName()+".json";
// write the POJO as the document content
docMgr.writeAs(docId, product);
// ... at some other time ...
// read the POJO from the document content
product = docMgr.readAs(docId, Product.class);
// log the persisted Json document
System.out.println(docMgr.readAs(docId, String.class));
// release the client
client.release();
}
}
如果我在这个例子中错了,请让我知道正确的方式,并帮助我解决这个问题。
感谢您的阅读。
答
尽管您可以使用JAXB将您的pojo序列化为JSON,但许多人更喜欢Jackson和我们的JacksonDatabindHandle。请参阅example in JacksonDatabindTest并注意the City class is registered on lines 68-69。或者,如果您不需要控制数据库中JSON的外观,最简单的方法是使用POJO Data Binding Interface。
谢谢Sam的回复。我会试用JacksonDataBindTest。我尝试了POJO与接口绑定的例子。这种方法有一个问题,我们如何在保存文档时设置文档的uri? – RCS
Sam,我尝试了JacksonDataBind示例并能够将pojo插入到marklogic数据库中。在更新(添加一个属性)的情况下需要一个建议现有文档。有两种方法我可以想到,要么我会更新POJO,并将其写回到DB或我会做部分更新,如JSON修补程序示例。考虑到我有大量数据需要处理,哪种方法更好,性能更好。 – RCS
您不需要使用PojoRepository来设置uri,它是基于类名和唯一标识(标记为@Id标注)为您设置的。 –