Sin categoría

Advanced Spring Data Couchbase

Lectura de 4 minutos

In the previous two posts we looked at getting started with Spring Data Couchbase. Now it’s time to get a little more sophisticated (keeping in mind that sophisticated or advanced does not mean more complicated). Let’s look at some of the great stuff you can do like caching, document validation and exposing your repository through a REST API.

Caching

The Spring core module provides a very nice cache abstraction with support for JSR–107(JCache). Let’s go through an example. To make sure the result of a method is cached, I can simply use the following annotation:

@Cacheable(value = “myCache”, key = “‘cache:’+#param”)
public Object useALotOfCPUCycles(String param){
 ….

}

Here “myCache” is the name of an existing cache instance I have configured. The key of the document will be resolved using the key regex “‘cache:’+#param”, where #param is the method parameter named ‘param’. This will make sure that for the same parameter, the method will be executed only once. When it’s called in future, the result will be fetched from the cache. Which is to say from Couchbase if I have configured my application appropriately. To define a cache instance, add the following to your configuration:


@Bean

CouchbaseCacheManager cacheManager(CouchbaseClient couchbaseClient) throws Exception {

    HashMap<String, CouchbaseClient> instances = new HashMap<>();

    instances.put(“myCache”, couchbaseClient);

    return new CouchbaseCacheManager(instances);

}

and the @EnableCaching annotation on your configuration class.

If you are already using Spring’s caching system, it is really easy to replace your current storage with Couchbase. Just make sure that the cacheManager you are using is a CouchbaseCacheManager implementation.

Document Validation

Field validation is a common task when dealing with business objects. An example would be to make sure that a specified field is not null before storing it into Couchbase, or that a field is not longer than 140 characters. And the good news is this is actually quite easy. I can use Hibernate validation. First thing to do is to add the required dependency to my pom:


    org.hibernate
    hibernate-validator

The next step is to add a ValidationListener bean that will throw a ConstraintViolationException when the object to be stored does not meet the validation requirement:

@Bean

LocalValidatorFactoryBean validator() {

    return new LocalValidatorFactoryBean();

}



@Bean 
ValidatingCouchbaseEventListener validationEventListener() { 
    return new ValidatingCouchbaseEventListener(validator());
 }

Now the mandatory configuration is done, I can add any Hibernate validation annotation to my POJO object like this:

@Field @NotNull
private String thisFieldShouldNotBeNull;

Now each time my application attempts to save an object where this particularly  property is set to null I will get a ConstraintViolationException.

There are of course plenty of annotations other than @NotNull. You can find them in the Spring documentation.

Expose the Repository with a REST API

Having a repository available in such a short amount of time is great, but what is even better is the fact that you can expose it behind a REST API just by adding a dependency. It requires the use of spring-data-rest-webmvc. So I add it to my dependencies like this:


    org.springframework.data
    spring-data-rest-webmvc

And voilà (I feel entitled to write voila, you know, because of my French origin). All the objects in this repository are exposed HATEOAS style:

caolila:~ ldoguin$ curl -v https://localhost:8080/twitterUpdates
{
 “_embedded” : {
    “twitterUpdates” : [ {
     “createdAt” : 1421929099417,
     “type” : “twitterUpdate”,
     “account” : “Couchbase”,
     “followers” : 90323,
     “favorites” : 619,
     “friends” : 541,
     “statuses” : 6155,
     “_links” : {
       “self” : {
         “href” : “https://localhost:8080/twitterUpdates/tw-couchbase–1421929099417”
       }
     }
    }, {
     “createdAt” : 1422314903175,
     “type” : “twitterUpdate”,
     “account” : “Couchbase”,
     “followers” : 90285,
     “favorites” : 619,
     “friends” : 542,
     “statuses” : 6207,
     “_links” : {
       “self” : {
         “href” : “https://localhost:8080/twitterUpdates/tw-Couchbase–1422314903175”
       }
     }
    } ]
 }

Just don’t forget to add getters like I did if you want to see some properties in your JSON documents…

That’s it for this blog post series about Spring Data Couchbase. Please comment and share, tell us if you want more Spring and Couchbase resources, tell us if you use it or want to use it.

Compartir este artículo

Autor

Laurent is a nerdy metal head who lives in Paris. He mostly writes code in Java and structured text in AsciiDoc, and often talks about data, reactive programming and other buzzwordy stuff. He is also a former Developer Advocate for Clever Cloud and Nuxeo where he devoted his time and expertise to helping those communities grow bigger and stronger. He now runs Developer Relations at Couchbase.

Una respuesta

  1. Avatar de Matthew Fontana
    Matthew Fontana

    Do you have the link to your source code for this project? I am having some issues getting the Spring-data-rest-webmvc dependency to expose my repository

Deja un comentario

¿Listo para comenzar con Couchbase Capella?

Comenzar a construir

Visita nuestro portal para desarrolladores para explorar NoSQL, consultar recursos y comenzar con los tutoriales.

Usa Capella gratis

Empieza a usar Couchbase en tan solo unos clics. Capella DBaaS es la forma más fácil y rápida de comenzar.

Ponte en contacto

¿Quieres saber más sobre las ofertas de Couchbase? Permítenos ayudarte.