Couchbase repositories

The goal of Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores.spring-doc.cn

By default, operations are backed by Key/Value if they are single-document operations and the ID is known. For all other operations by default N1QL queries are generated, and as a result proper indexes must be created for performant data access.spring-doc.cn

Note that you can tune the consistency you want for your queries (see Querying with consistency) and have different repositories backed by different buckets (see [couchbase.repository.multibucket])spring-doc.cn

Configuration

While support for repositories is always present, you need to enable them in general or for a specific namespace. If you extend AbstractCouchbaseConfiguration, just use the @EnableCouchbaseRepositories annotation. It provides lots of possible options to narrow or customize the search path, one of the most common ones is basePackages.spring-doc.cn

Also note that if you are running inside spring boot, the autoconfig support already sets up the annotation for you so you only need to use it if you want to override the defaults.spring-doc.cn

Example 1. Annotation-Based Repository Setup
@Configuration
@EnableCouchbaseRepositories(basePackages = {"com.couchbase.example.repos"})
public class Config extends AbstractCouchbaseConfiguration {
    //...
}

An advanced usage is described in [couchbase.repository.multibucket].spring-doc.cn

QueryDSL Configuration

Spring Data Couchbase supports QueryDSL for building type-safe queries. To enable code generation, setting CouchbaseAnnotationProcessor as an annotation processor is required. Additionally, the runtime needs querydsl-apt to enable QueryDSL on repositories.spring-doc.cn

Example 2. Maven Configuration Example
    . existing depdendencies including those required for spring-data-couchbase
    .
    .
    <dependency>
        <groupId>com.querydsl</groupId>
        <artifactId>querydsl-apt</artifactId>
        <version>${querydslVersion}</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
                <executions>
                    <execution>
                        <id>annotation-processing</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                        <configuration>
                            <proc>only</proc>
                            <annotationProcessors>
                                <annotationProcessor>org.springframework.data.couchbase.repository.support.CouchbaseAnnotationProcessor</annotationProcessor>
                            </annotationProcessors>
                            <generatedTestSourcesDirectory>target/generated-sources</generatedTestSourcesDirectory>
                            <compilerArgs>
                                <arg>-Aquerydsl.logInfo=true</arg>
                            </compilerArgs>
                        </configuration>
                    </execution>
                </executions>
        </plugin>
    </plugins>
</build>
Example 3. Gradle Configuration Example
dependencies {
    annotationProcessor 'com.querydsl:querydsl-apt:${querydslVersion}'
    annotationProcessor 'org.springframework.data:spring-data-couchbase'
    testAnnotationProcessor 'com.querydsl:querydsl-apt:${querydslVersion}'
    testAnnotationProcessor 'org.springframework.data:spring-data-couchbase'
}
tasks.withType(JavaCompile).configureEach {
    options.compilerArgs += [
            "-processor",
            "org.springframework.data.couchbase.repository.support.CouchbaseAnnotationProcessor"]
}

Usage

In the simplest case, your repository will extend the CrudRepository<T, String>, where T is the entity that you want to expose. Let’s look at a repository for a UserInfo:spring-doc.cn

Example 4. A UserInfo repository
import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<UserInfo, String> {
}

Please note that this is just an interface and not an actual class. In the background, when your context gets initialized, actual implementations for your repository descriptions get created and you can access them through regular beans. This means you will save lots of boilerplate code while still exposing full CRUD semantics to your service layer and application.spring-doc.cn

Now, let’s imagine we @Autowire the UserRepository to a class that makes use of it. What methods do we have available?spring-doc.cn

Table 1. Exposed methods on the UserRepository
Method Description

UserInfo save(UserInfo entity)spring-doc.cn

Save the given entity.spring-doc.cn

Iterable<UserInfo> save(Iterable<UserInfo> entity)spring-doc.cn

Save the list of entities.spring-doc.cn

UserInfo findOne(String id)spring-doc.cn

Find a entity by its unique id.spring-doc.cn

boolean exists(String id)spring-doc.cn

Check if a given entity exists by its unique id.spring-doc.cn

Iterable<UserInfo> findAll()spring-doc.cn

Find all entities by this type in the bucket.spring-doc.cn

Iterable<UserInfo> findAll(Iterable<String> ids)spring-doc.cn

Find all entities by this type and the given list of ids.spring-doc.cn

long count()spring-doc.cn

Count the number of entities in the bucket.spring-doc.cn

void delete(String id)spring-doc.cn

Delete the entity by its id.spring-doc.cn

void delete(UserInfo entity)spring-doc.cn

Delete the entity.spring-doc.cn

void delete(Iterable<UserInfo> entities)spring-doc.cn

Delete all given entities.spring-doc.cn

void deleteAll()spring-doc.cn

Delete all entities by type in the bucket.spring-doc.cn

Now that’s awesome! Just by defining an interface we get full CRUD functionality on top of our managed entity.spring-doc.cn

While the exposed methods provide you with a great variety of access patterns, very often you need to define custom ones. You can do this by adding method declarations to your interface, which will be automatically resolved to requests in the background, as we’ll see in the next sections.spring-doc.cn

Repositories and Querying

N1QL based querying

Prerequisite is to have created a PRIMARY INDEX on the bucket where the entities will be stored.spring-doc.cn

Here is an example:spring-doc.cn

Example 5. An extended UserInfo repository with N1QL queries
public interface UserRepository extends CrudRepository<UserInfo, String> {

    @Query("#{#n1ql.selectEntity} WHERE role = 'admin' AND #{#n1ql.filter}")
    List<UserInfo> findAllAdmins();

    List<UserInfo> findByFirstname(String fname);
}

Here we see two N1QL-backed ways of querying.spring-doc.cn

The first method uses the Query annotation to provide a N1QL statement inline. SpEL (Spring Expression Language) is supported by surrounding SpEL expression blocks between #{ and }. A few N1QL-specific values are provided through SpEL:spring-doc.cn

  • #n1ql.selectEntity allows to easily make sure the statement will select all the fields necessary to build the full entity (including document ID and CAS value).spring-doc.cn

  • #n1ql.filter in the WHERE clause adds a criteria matching the entity type with the field that Spring Data uses to store type information.spring-doc.cn

  • #n1ql.bucket will be replaced by the name of the bucket the entity is stored in, escaped in backticks.spring-doc.cn

  • #n1ql.scope will be replaced by the name of the scope the entity is stored in, escaped in backticks.spring-doc.cn

  • #n1ql.collection will be replaced by the name of the collection the entity is stored in, escaped in backticks.spring-doc.cn

  • #n1ql.fields will be replaced by the list of fields (eg. for a SELECT clause) necessary to reconstruct the entity.spring-doc.cn

  • #n1ql.delete will be replaced by the delete from statement.spring-doc.cn

  • #n1ql.returning will be replaced by returning clause needed for reconstructing entity.spring-doc.cn

We recommend that you always use the selectEntity SpEL and a WHERE clause with a filter SpEL (since otherwise your query could be impacted by entities from other repositories).

String-based queries support parametrized queries. You can either use positional placeholders like “$1”, in which case each of the method parameters will map, in order, to $1, $2, $3…​ Alternatively, you can use named placeholders using the “$someString” syntax. Method parameters will be matched with their corresponding placeholder using the parameter’s name, which can be overridden by annotating each parameter (except a Pageable or Sort) with @Param (eg. @Param("someString")). You cannot mix the two approaches in your query and will get an IllegalArgumentException if you do.spring-doc.cn

Note that you can mix N1QL placeholders and SpEL. N1QL placeholders will still consider all method parameters, so be sure to use the correct index like in the example below:spring-doc.cn

Example 6. An inline query that mixes SpEL and N1QL placeholders
@Query("#{#n1ql.selectEntity} WHERE #{#n1ql.filter} AND #{[0]} = $2")
public List<User> findUsersByDynamicCriteria(String criteriaField, Object criteriaValue)

This allows you to generate queries that would work similarly to eg. AND name = "someName" or AND age = 3, with a single method declaration.spring-doc.cn

You can also do single projections in your N1QL queries (provided it selects only one field and returns only one result, usually an aggregation like COUNT, AVG, MAX…​). Such projection would have a simple return type like long, boolean or String. This is NOT intended for projections to DTOs.spring-doc.cn

Another example:
#{#n1ql.selectEntity} WHERE #{#n1ql.filter} AND test = $1
is equivalent to
SELECT #{#n1ql.fields} FROM #{#n1ql.collection} WHERE #{#n1ql.filter} AND test = $1spring-doc.cn

A practical application of SpEL with Spring Security

SpEL can be useful when you want to do a query depending on data injected by other Spring components, like Spring Security. Here is what you need to do to extend the SpEL context to get access to such external data.spring-doc.cn

First, you need to implement an EvaluationContextExtension (use the support class as below):spring-doc.cn

class SecurityEvaluationContextExtension extends EvaluationContextExtensionSupport {

  @Override
  public String getExtensionId() {
    return "security";
  }

  @Override
  public SecurityExpressionRoot getRootObject() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return new SecurityExpressionRoot(authentication) {};
  }
}

Then all you need to do for Spring Data Couchbase to be able to access associated SpEL values is to declare a corresponding bean in your configuration:spring-doc.cn

@Bean
EvaluationContextExtension securityExtension() {
    return new SecurityEvaluationContextExtension();
}

This could be useful to craft a query according to the role of the connected user for instance:spring-doc.cn

@Query("#{#n1ql.selectEntity} WHERE #{#n1ql.filter} AND " +
"role = '?#{hasRole('ROLE_ADMIN') ? 'public_admin' : 'admin'}'")
List<UserInfo> findAllAdmins(); //only ROLE_ADMIN users will see hidden admins

Delete query example:spring-doc.cn

@Query("#{#n1ql.delete} WHERE #{#n1ql.filter} AND " +
"username = $1 #{#n1ql.returning}")
UserInfo removeUser(String username);

The second method uses Spring-Data’s query derivation mechanism to build a N1QL query from the method name and parameters. This will produce a query looking like this: SELECT …​ FROM …​ WHERE firstName = "valueOfFnameAtRuntime". You can combine these criteria, even do a count with a name like countByFirstname or a limit with a name like findFirst3ByLastname…​spring-doc.cn

Actually the generated N1QL query will also contain an additional N1QL criteria in order to only select documents that match the repository’s entity class.

Most Spring-Data keywords are supported: .Supported keywords inside @Query (N1QL) method namesspring-doc.cn

Keyword Sample N1QL WHERE clause snippet

Andspring-doc.cn

findByLastnameAndFirstnamespring-doc.cn

lastName = a AND firstName = bspring-doc.cn

Orspring-doc.cn

findByLastnameOrFirstnamespring-doc.cn

lastName = a OR firstName = bspring-doc.cn

Is,Equalsspring-doc.cn

findByField,findByFieldEqualsspring-doc.cn

field = aspring-doc.cn

IsNot,Notspring-doc.cn

findByFieldIsNotspring-doc.cn

field != aspring-doc.cn

Betweenspring-doc.cn

findByFieldBetweenspring-doc.cn

field BETWEEN a AND bspring-doc.cn

IsLessThan,LessThan,IsBefore,Beforespring-doc.cn

findByFieldIsLessThan,findByFieldBeforespring-doc.cn

field < aspring-doc.cn

IsLessThanEqual,LessThanEqualspring-doc.cn

findByFieldIsLessThanEqualspring-doc.cn

field ⇐ aspring-doc.cn

IsGreaterThan,GreaterThan,IsAfter,Afterspring-doc.cn

findByFieldIsGreaterThan,findByFieldAfterspring-doc.cn

field > aspring-doc.cn

IsGreaterThanEqual,GreaterThanEqualspring-doc.cn

findByFieldGreaterThanEqualspring-doc.cn

field >= aspring-doc.cn

IsNullspring-doc.cn

findByFieldIsNullspring-doc.cn

field IS NULLspring-doc.cn

IsNotNull,NotNullspring-doc.cn

findByFieldIsNotNullspring-doc.cn

field IS NOT NULLspring-doc.cn

IsLike,Likespring-doc.cn

findByFieldLikespring-doc.cn

field LIKE "a" - a should be a String containing % and _ (matching n and 1 characters)spring-doc.cn

IsNotLike,NotLikespring-doc.cn

findByFieldNotLikespring-doc.cn

field NOT LIKE "a" - a should be a String containing % and _ (matching n and 1 characters)spring-doc.cn

IsStartingWith,StartingWith,StartsWithspring-doc.cn

findByFieldStartingWithspring-doc.cn

field LIKE "a%" - a should be a String prefixspring-doc.cn

IsEndingWith,EndingWith,EndsWithspring-doc.cn

findByFieldEndingWithspring-doc.cn

field LIKE "%a" - a should be a String suffixspring-doc.cn

IsContaining,Containing,Containsspring-doc.cn

findByFieldContainsspring-doc.cn

field LIKE "%a%" - a should be a Stringspring-doc.cn

IsNotContaining,NotContaining,NotContainsspring-doc.cn

findByFieldNotContainingspring-doc.cn

field NOT LIKE "%a%" - a should be a Stringspring-doc.cn

IsIn,Inspring-doc.cn

findByFieldInspring-doc.cn

field IN array - note that the next parameter value (or its children if a collection/array) should be compatible for storage in a JsonArray)spring-doc.cn

IsNotIn,NotInspring-doc.cn

findByFieldNotInspring-doc.cn

field NOT IN array - note that the next parameter value (or its children if a collection/array) should be compatible for storage in a JsonArray)spring-doc.cn

IsTrue,Truespring-doc.cn

findByFieldIsTruespring-doc.cn

field = TRUEspring-doc.cn

IsFalse,Falsespring-doc.cn

findByFieldFalsespring-doc.cn

field = FALSEspring-doc.cn

MatchesRegex,Matches,Regexspring-doc.cn

findByFieldMatchesspring-doc.cn

REGEXP_LIKE(field, "a") - note that the ignoreCase is ignored here, a is a regular expression in String formspring-doc.cn

Existsspring-doc.cn

findByFieldExistsspring-doc.cn

field IS NOT MISSING - used to verify that the JSON contains this attributespring-doc.cn

OrderByspring-doc.cn

findByFieldOrderByLastnameDescspring-doc.cn

field = a ORDER BY lastname DESCspring-doc.cn

IgnoreCasespring-doc.cn

findByFieldIgnoreCasespring-doc.cn

LOWER(field) = LOWER("a") - a must be a Stringspring-doc.cn

You can use both counting queries and [repositories.limit-query-result] features with this approach.spring-doc.cn

With N1QL, another possible interface for the repository is the PagingAndSortingRepository one (which extends CrudRepository). It adds two methods:spring-doc.cn

Table 2. Exposed methods on the PagingAndSortingRepository
Method Description

Iterable<T> findAll(Sort sort);spring-doc.cn

Allows to retrieve all relevant entities while sorting on one of their attributes.spring-doc.cn

Page<T> findAll(Pageable pageable);spring-doc.cn

Allows to retrieve your entities in pages. The returned Page allows to easily get the next page’s Pageable as well as the list of items. For the first call, use new PageRequest(0, pageSize) as Pageable.spring-doc.cn

You can also use Page and Slice as method return types as well with a N1QL backed repository.
If pageable and sort parameters are used with inline queries, there should not be any order by, limit or offset clause in the inline query itself otherwise the server would reject the query as malformed.

Automatic Index Management

By default, it is expected that the user creates and manages optimal indexes for their queries. Especially in the early stages of development, it can come in handy to automatically create indexes to get going quickly.spring-doc.cn

For N1QL, the following annotations are provided which need to be attached to the entity (either on the class or the field):spring-doc.cn

  • @QueryIndexed: Placed on a field to signal that this field should be part of the indexspring-doc.cn

  • @CompositeQueryIndex: Placed on the class to signal that an index on more than one field (composite) should be created.spring-doc.cn

  • @CompositeQueryIndexes: If more than one CompositeQueryIndex should be created, this annotation will take a list of them.spring-doc.cn

For example, this is how you define a composite index on an entity:spring-doc.cn

Example 7. Composite index on two fields with ordering
@Document
@CompositeQueryIndex(fields = {"id", "name desc"})
public class Airline {
   @Id
   String id;

	@QueryIndexed
	String name;

	@PersistenceConstructor
	public Airline(String id, String name) {
		this.id = id;
	}

	public String getId() {
		return id;
	}

	public String getName() {
		return name;
	}

}

By default, index creation is disabled. If you want to enable it you need to override it on the configuration:spring-doc.cn

Example 8. Enable auto index creation
@Override
protected boolean autoIndexCreation() {
 return true;
}

Querying with consistency

By default repository queries that use N1QL use the NOT_BOUNDED scan consistency. This means that results return quickly, but the data from the index may not yet contain data from previously written operations (called eventual consistency). If you need "ready your own write" semantics for a query, you need to use the @ScanConsistency annotation. Here is an example:spring-doc.cn

Example 9. Using a different scan consistency
@Repository
public interface AirportRepository extends PagingAndSortingRepository<Airport, String> {

	@Override
	@ScanConsistency(query = QueryScanConsistency.REQUEST_PLUS)
	Iterable<Airport> findAll();

}

DTO Projections

Spring Data Repositories usually return the domain model when using query methods. However, sometimes, you may need to alter the view of that model for various reasons. In this section, you will learn how to define projections to serve up simplified and reduced views of resources.spring-doc.cn

Look at the following domain model:spring-doc.cn

@Entity
public class Person {

  @Id @GeneratedValue
  private Long id;
  private String firstName, lastName;

  @OneToOne
  private Address address;
  …
}

@Entity
public class Address {

  @Id @GeneratedValue
  private Long id;
  private String street, state, country;

  …
}

This Person has several attributes:spring-doc.cn

Now assume we create a corresponding repository as follows:spring-doc.cn

interface PersonRepository extends CrudRepository<Person, Long> {

  Person findPersonByFirstName(String firstName);
}

Spring Data will return the domain object including all of its attributes. There are two options just to retrieve the address attribute. One option is to define a repository for Address objects like this:spring-doc.cn

interface AddressRepository extends CrudRepository<Address, Long> {}

In this situation, using PersonRepository will still return the whole Person object. Using AddressRepository will return just the Address.spring-doc.cn

However, what if you do not want to expose address details at all? You can offer the consumer of your repository service an alternative by defining one or more projections.spring-doc.cn

Example 10. Simple Projection
interface NoAddresses {  (1)

  String getFirstName(); (2)

  String getLastName();  (3)
}

This projection has the following details:spring-doc.cn

1 A plain Java interface making it declarative.
2 Export the firstName.
3 Export the lastName.

The NoAddresses projection only has getters for firstName and lastName meaning that it will not serve up any address information. The query method definition returns in this case NoAdresses instead of Person.spring-doc.cn

interface PersonRepository extends CrudRepository<Person, Long> {

  NoAddresses findByFirstName(String firstName);
}

Projections declare a contract between the underlying type and the method signatures related to the exposed properties. Hence it is required to name getter methods according to the property name of the underlying type. If the underlying property is named firstName, then the getter method must be named getFirstName otherwise Spring Data is not able to look up the source property.spring-doc.cn