Couchbase Documents and Repositories
Explore documents and repositories through the Spring Data Couchbase framework.
Couchbase documents are JSON-based data structures that represent database records and repositories and provide an abstraction layer to interact with documents using high-level APIs and query methods for CRUD operations.
Documents
Let’s cover the same example of the Book
and Author
POJOs referencing the book
and author
database documents and convert them into Couchbase document classes.
The Book
document
Let’s learn a few handy annotations to transform a POJO into a Couchbase document.
The most common annotations are @Document
and @Id
.
-
The
@Document
annotation allows mapping a POJO to a database document by the underlying data access layer. -
The
@Id
annotation allows mapping a property to an identifier in the database document.
We can use these annotations to convert the Book
POJO from the com.smartdiscover.model
package to a Couchbase document and map it to the book
document:
package com.smartdiscover.model;import lombok.Data;import org.springframework.data.annotation.*;import org.springframework.data.couchbase.core.mapping.Document;import org.springframework.data.couchbase.core.mapping.Field;import org.springframework.data.couchbase.core.mapping.id.GeneratedValue;import org.springframework.data.couchbase.core.mapping.id.GenerationStrategy;import java.util.Date;import java.util.List;import java.util.stream.Collectors;import java.util.List;@Data@Documentpublic class Book {@Id@GeneratedValue(strategy = GenerationStrategy.UNIQUE)private String id;private String name;private String summary;private List<Author> authors;@Overridepublic String toString() {return "Book{" +"id=" + id +", name='" + name + '\'' +", summary='" + summary + '\'' +((null != authors) ? ", authors=" + authors.stream().map(i -> i.getFullName()).collect(Collectors.toList()) + '\'' : "") +'}';}}
Here’s an explanation of the code:
-
...