미분류

Advanced Spring Data Couchbase

4 분 읽기

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.

이 기사 공유하기

작가

로랑은 파리에 사는 찌질한 매니아 기질이 있는 헤비메탈 마니아입니다. 그는 주로 자바(Java)로 코드를 작성하고 AsciiDoc으로 구조화된 텍스트를 작성하며, 데이터, 리액티브 프로그래밍 및 기타 유행어 같은 주제에 대해 자주 이야기합니다. 그는 또한 Clever Cloud와 Nuxeo의 전직 개발자 애드보케이트로 활동하며 해당 커뮤니티가 더 크고 강하게 성장하도록 시간과 전문 지식을 쏟아부었습니다. 현재는 카우치베이스(Couchbase)에서 개발자 관계(Developer Relations)를 총괄하고 있습니다.

1개의 응답

  1. 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

댓글 남기기

카우치베이스 카펠라를 시작할 준비가 되셨나요?

개발 시작하기

NoSQL을 탐색하고, 리소스를 찾아보고, 튜토리얼을 시작하려면 개발자 포털을 확인하세요.

카펠라 프리 사용하기

단 몇 번의 클릭으로 카우치베이스(Couchbase)를 직접 체험해 보세요. Capella DBaaS는 시작하기 가장 쉽고 빠른 방법입니다.

연락해

Couchbase 제품군에 대해 더 알고 싶으신가요? 저희가 도와드리겠습니다.