1. Introduction
1.介绍
In this tutorial on Spring Data, we’ll discuss how to set up a persistence layer for Couchbase documents using both the Spring Data repository and template abstractions, as well as the steps required to prepare Couchbase to support these abstractions using views and/or indexes.
在这个关于Spring Data的教程中,我们将讨论如何使用Spring Data资源库和模板抽象为Couchbase文档建立一个持久层,以及准备Couchbase使用视图和/或索引支持这些抽象所需的步骤。
2. Maven Dependencies
2.Maven的依赖性
First, we add the following Maven dependency to our pom.xml file:
首先,我们在pom.xml文件中添加以下Maven依赖项。
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-couchbase</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
Note that by including this dependency, we automatically get a compatible version of the native Couchbase SDK, so we need not include it explicitly.
请注意,通过包含这个依赖关系,我们会自动得到一个兼容的本地Couchbase SDK版本,所以我们不需要明确地包含它。
To add support for JSR-303 bean validation, we also include the following dependency:
为了增加对JSR-303 Bean验证的支持,我们还包括以下依赖关系。
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>
Spring Data Couchbase supports date and time persistence via the traditional Date and Calendar classes, as well as via the Joda Time library, which we include as follows:
Spring Data Couchbase通过传统的Date和Calendar类以及Joda Time库来支持日期和时间的持久性,我们将其包含在下面。
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.2</version>
</dependency>
3. Configuration
3.配置
Next, we’ll need to configure the Couchbase environment by specifying one or more nodes of our Couchbase cluster and the name and password of the bucket in which we will store our documents.
接下来,我们需要配置Couchbase环境,指定Couchbase集群的一个或多个节点,以及我们将存储文档的桶的名称和密码。
3.1. Java Configuration
3.1. Java配置
For Java class configuration, we simply extend the AbstractCouchbaseConfiguration class:
对于Java类的配置,我们只需扩展AbstractCouchbaseConfiguration类。
@Configuration
@EnableCouchbaseRepositories(basePackages={"com.baeldung.spring.data.couchbase"})
public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration {
@Override
protected List<String> getBootstrapHosts() {
return Arrays.asList("localhost");
}
@Override
protected String getBucketName() {
return "baeldung";
}
@Override
protected String getBucketPassword() {
return "";
}
}
If your project requires more customization of the Couchbase environment, you may provide one by overriding the getEnvironment() method:
如果你的项目需要对Couchbase环境进行更多的定制,你可以通过重写getEnvironment()方法来提供一个。
@Override
protected CouchbaseEnvironment getEnvironment() {
...
}
3.2. XML Configuration
3.2.XML配置
Here is the equivalent configuration in XML:
下面是XML中的同等配置。
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/data/couchbase
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/couchbase
http://www.springframework.org/schema/data/couchbase/spring-couchbase.xsd">
<couchbase:cluster>
<couchbase:node>localhost</couchbase:node>
</couchbase:cluster>
<couchbase:clusterInfo login="baeldung" password="" />
<couchbase:bucket bucketName="baeldung" bucketPassword=""/>
<couchbase:repositories base-package="com.baeldung.spring.data.couchbase"/>
</beans:beans>
Note: the “clusterInfo” node accepts either cluster credentials or bucket credentials and is required so that the library can determine whether or not your Couchbase cluster supports N1QL (a superset of SQL for NoSQL databases, available in Couchbase 4.0 and later).
注意:”clusterInfo“节点接受集群凭证或桶凭证,并且是必须的,以便库可以确定你的Couchbase集群是否支持N1QL(NoSQL数据库的SQL超集,在Couchbase 4.0及以后版本中可用)。
If your project requires a custom Couchbase environment, you may provide one using the <couchbase:env/> tag.
如果你的项目需要一个自定义的Couchbase环境,你可以使用<couchbase:env/>标签提供一个。
4. Data Model
4.数据模型
Let’s create an entity class representing the JSON document to persist. We first annotate the class with @Document, and then we annotate a String field with @Id to represent the Couchbase document key.
让我们创建一个代表JSON文档的实体类来持久化。我们首先用@Document,注解这个类,然后用@Id注解一个String字段来表示Couchbase文档的键。
You may use either the @Id annotation from Spring Data or the one from the native Couchbase SDK. Be advised that if you use both @Id annotations in the same class on two different fields, then the field annotated with the Spring Data @Id annotation will take precedence and will be used as the document key.
你可以使用Spring Data的@Id注解,或者使用本地Couchbase SDK的注解。请注意,如果你在同一个类中对两个不同的字段同时使用@Id注解,那么用Spring Data的@Id注解的字段将被优先使用,并将被用作文档键。
To represent the JSON documents’ attributes, we add private member variables annotated with @Field. We use the @NotNull annotation to mark certain fields as required:
为了表示JSON文档的属性,我们添加了用@Field注释的私有成员变量。我们使用@NotNull注解来标记某些字段为必需。
@Document
public class Person {
@Id
private String id;
@Field
@NotNull
private String firstName;
@Field
@NotNull
private String lastName;
@Field
@NotNull
private DateTime created;
@Field
private DateTime updated;
// standard getters and setters
}
Note that the property annotated with @Id merely represents the document key and is not necessarily part of the stored JSON document unless it is also annotated with @Field as in:
请注意,用@Id注释的属性只是代表文档密钥,不一定是存储的JSON文档的一部分,除非它也用@Field注释,如:。
@Id
@Field
private String id;
If you want to name a field in the entity class differently from what is to be stored in the JSON document, simply qualify its @Field annotation, as in this example:
如果你想在实体类中命名一个字段,与存储在JSON文档中的不同,只需限定其@Field注解,如本例。
@Field("fname")
private String firstName;
Here is an example showing how a persisted Person document would look:
下面是一个例子,显示了一个持久化的Person文档的样子。
{
"firstName": "John",
"lastName": "Smith",
"created": 1457193705667
"_class": "com.baeldung.spring.data.couchbase.model.Person"
}
Notice that Spring Data automatically adds to each document an attribute containing the full class name of the entity. By default, this attribute is named “_class”, although you can override that in your Couchbase configuration class by overriding the typeKey() method.
请注意,Spring Data会自动给每个文档添加一个包含实体全类名称的属性。默认情况下,这个属性被命名为“_class”,尽管你可以通过覆盖typeKey()方法在你的Couchbase配置类中覆盖它。
For example, if you want to designate a field named “dataType” to hold the class names, you would add this to your Couchbase configuration class:
例如,如果你想指定一个名为“dataType”的字段来保存类的名称,你可以将其添加到Couchbase的配置类中。
@Override
public String typeKey() {
return "dataType";
}
Another popular reason to override typeKey() is if you are using a version of Couchbase Mobile that does not support fields prefixed with the underscore. In this case, you can choose your own alternate type field as in the previous example, or you can use an alternate provided by Spring:
覆盖typeKey()的另一个流行原因是,如果你使用的Couchbase Mobile版本不支持以下划线为前缀的字段。在这种情况下,你可以像前面的例子一样选择你自己的替代类型字段,或者你可以使用Spring提供的替代类型。
@Override
public String typeKey() {
// use "javaClass" instead of "_class"
return MappingCouchbaseConverter.TYPEKEY_SYNCGATEWAY_COMPATIBLE;
}
5. Couchbase Repository
5.Couchbase存储库
Spring Data Couchbase provides the same built-in queries and derived query mechanisms as other Spring Data modules such as JPA.
Spring Data Couchbase提供了与其他Spring Data模块(如JPA)一样的内置查询和派生查询机制。
We declare a repository interface for the Person class by extending CrudRepository<String,Person> and adding a derivable query method:
我们通过扩展CrudRepository<String,Person>,为Person类声明一个存储库接口,并添加一个可衍生的查询方法。
public interface PersonRepository extends CrudRepository<Person, String> {
List<Person> findByFirstName(String firstName);
}
6. N1QL Support via Indexes
6.通过索引支持N1QL
If using Couchbase 4.0 or later, then by default, custom queries are processed using the N1QL engine (unless their corresponding repository methods are annotated with @View to indicate the use of backing views as described in the next section).
如果使用Couchbase 4.0或更高版本,那么默认情况下,自定义查询是使用N1QL引擎来处理的(除非其对应的存储库方法被注释为@View以表示使用支持视图,如下一节所述)。
To add support for N1QL, you must create a primary index on the bucket. You may create the index by using the cbq command-line query processor (see your Couchbase documentation on how to launch the cbq tool for your environment) and issuing the following command:
为了增加对N1QL的支持,你必须在桶上创建一个主索引。你可以通过使用cbq命令行查询处理器来创建索引(关于如何为你的环境启动cbq工具,请参见你的Couchbase文档)并发出以下命令。
CREATE PRIMARY INDEX ON baeldung USING GSI;
In the above command, GSI stands for global secondary index, which is a type of index particularly suited for optimization of ad hoc N1QL queries in support of OLTP systems and is the default index type if not otherwise specified.
在上述命令中,GSI代表全局二级索引,这是一种特别适合优化支持OLTP系统的临时N1QL查询的索引类型,如果没有另外指定,它是默认的索引类型。
Unlike view-based indexes, GSI indexes are not automatically replicated across all index nodes in a cluster, so if your cluster contains more than one index node, you will need to create each GSI index on each node in the cluster, and you must provide a different index name on each node.
与基于视图的索引不同,GSI索引不会在集群中的所有索引节点上自动复制,因此,如果你的集群包含一个以上的索引节点,你需要在集群中的每个节点上创建每个GSI索引,而且你必须在每个节点上提供一个不同的索引名称。
You may also create one or more secondary indexes. When you do, Couchbase will use them as needed in order to optimize its query processing.
你也可以创建一个或多个二级索引。当你这样做的时候,Couchbase会根据需要使用它们,以优化其查询处理。
For example, to add an index on the firstName field, issue the following command in the cbq tool:
例如,为了在firstName字段上添加索引,在cbq工具中发出以下命令。
CREATE INDEX idx_firstName ON baeldung(firstName) USING GSI;
7. Backing Views
7.支持的观点
For each repository interface, you will need to create a Couchbase design document and one or more views in the target bucket. The design document name must be the lowerCamelCase version of the entity class name (e.g. “person”).
对于每个存储库接口,你需要在目标桶中创建一个Couchbase设计文档和一个或多个视图。设计文档的名称必须是实体类名称的lowerCamelCase版本(例如,“person”)。
Regardless of which version of Couchbase Server you are running, you must create a backing view named “all” to support the built-in “findAll” repository method. Here is the map function for the “all” view for our Person class:
无论你运行的是哪个版本的Couchbase服务器,你都必须创建一个名为“all”的支撑视图,以支持内置的”findAll”存储库方法。下面是我们的Person类的“all”视图的映射函数。
function (doc, meta) {
if(doc._class == "com.baeldung.spring.data.couchbase.model.Person") {
emit(meta.id, null);
}
}
Custom repository methods must each have a backing view when using a Couchbase version prior to 4.0 (the use of backing views is optional in 4.0 or later).
当使用4.0之前的Couchbase版本时,自定义存储库方法必须有一个支持视图(在4.0或更高版本中,支持视图的使用是可选的)。
View-backed custom methods must be annotated with @View as in the following example:
视图支持的自定义方法必须用@View来注解,如下例所示。
@View
List<Person> findByFirstName(String firstName);
The default naming convention for backing views is to use the lowerCamelCase version of that part of the method name following the “find” keyword (e.g. “byFirstName”).
支持视图的默认命名惯例是使用方法名称中”find”关键字之后的lowerCamelCase版本(例如,“byFirstName”)。
Here is how you would write the map function for the “byFirstName” view:
下面是你如何为“byFirstName”视图编写地图函数。
function (doc, meta) {
if(doc._class == "com.baeldung.spring.data.couchbase.model.Person"
&& doc.firstName) {
emit(doc.firstName, null);
}
}
You can override this naming convention and use your own view names by qualifying each @View annotation with the name of your corresponding backing view. For example:
你可以通过在每个@View注解中限定相应的支持视图的名称来覆盖这个命名惯例并使用你自己的视图名称。比如说。
@View("myCustomView")
List<Person> findByFirstName(String lastName);
8. Service Layer
8.服务层
For our service layer, we define an interface and two implementations: one using the Spring Data repository abstraction, and another using the Spring Data template abstraction. Here is our PersonService interface:
对于我们的服务层,我们定义了一个接口和两个实现:一个使用Spring Data资源库抽象,另一个使用Spring Data模板抽象。下面是我们的PersonService接口。
public interface PersonService {
Person findOne(String id);
List<Person> findAll();
List<Person> findByFirstName(String firstName);
void create(Person person);
void update(Person person);
void delete(Person person);
}
8.1. Repository Service
8.1.存储库服务
Here is an implementation using the repository we defined above:
下面是一个使用我们上面定义的存储库的实现。
@Service
@Qualifier("PersonRepositoryService")
public class PersonRepositoryService implements PersonService {
@Autowired
private PersonRepository repo;
public Person findOne(String id) {
return repo.findOne(id);
}
public List<Person> findAll() {
List<Person> people = new ArrayList<Person>();
Iterator<Person> it = repo.findAll().iterator();
while(it.hasNext()) {
people.add(it.next());
}
return people;
}
public List<Person> findByFirstName(String firstName) {
return repo.findByFirstName(firstName);
}
public void create(Person person) {
person.setCreated(DateTime.now());
repo.save(person);
}
public void update(Person person) {
person.setUpdated(DateTime.now());
repo.save(person);
}
public void delete(Person person) {
repo.delete(person);
}
}
8.2. Template Service
8.2.模板服务
For the template-based implementation, we must create the backing views listed in section 7 above. The CouchbaseTemplate object is available in our Spring context and may be injected into the service class.
对于基于模板的实现,我们必须创建上面第7节中列出的支持视图。CouchbaseTemplate对象在我们的Spring上下文中可用,可以被注入到服务类中。
Here is the implementation using the template abstraction:
下面是使用模板抽象的实现。
@Service
@Qualifier("PersonTemplateService")
public class PersonTemplateService implements PersonService {
private static final String DESIGN_DOC = "person";
@Autowired
private CouchbaseTemplate template;
public Person findOne(String id) {
return template.findById(id, Person.class);
}
public List<Person> findAll() {
return template.findByView(ViewQuery.from(DESIGN_DOC, "all"), Person.class);
}
public List<Person> findByFirstName(String firstName) {
return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName"), Person.class);
}
public void create(Person person) {
person.setCreated(DateTime.now());
template.insert(person);
}
public void update(Person person) {
person.setUpdated(DateTime.now());
template.update(person);
}
public void delete(Person person) {
template.remove(person);
}
}
9. Conclusion
9.结论
We have shown how to configure a project to use the Spring Data Couchbase module and how to write a simple entity class and its repository interface. We wrote a simple service interface and provided one implementation using the repository and another implementation using the Spring Data template API.
我们已经展示了如何配置一个项目来使用Spring Data Couchbase模块,以及如何编写一个简单的实体类及其存储库接口。我们写了一个简单的服务接口,并提供了一个使用存储库的实现和另一个使用Spring Data模板API的实现。
You can view the complete source code for this tutorial in the GitHub project.
你可以在GitHub项目中查看本教程的完整源代码。
For further information, visit the Spring Data Couchbase project site.
欲了解更多信息,请访问Spring Data Couchbase项目网站。