<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anastasiia Smirnova on Medium]]></title>
        <description><![CDATA[Stories by Anastasiia Smirnova on Medium]]></description>
        <link>https://medium.com/@anastasiiasmirnova?source=rss-982ae09f821b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7pIZNM18JiY8vCOW.</url>
            <title>Stories by Anastasiia Smirnova on Medium</title>
            <link>https://medium.com/@anastasiiasmirnova?source=rss-982ae09f821b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 13:55:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anastasiiasmirnova/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Real-world behind Schema first vs Code first (Part 2)]]></title>
            <link>https://medium.com/@anastasiiasmirnova/real-world-behind-design-first-vs-code-first-part-2-ccf3b2de0670?source=rss-982ae09f821b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccf3b2de0670</guid>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[design-first]]></category>
            <dc:creator><![CDATA[Anastasiia Smirnova]]></dc:creator>
            <pubDate>Wed, 21 Sep 2022 16:09:05 GMT</pubDate>
            <atom:updated>2022-09-21T16:42:11.451Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MxFkQ-n4noZwLwkCDeuB9w.jpeg" /></figure><p>First part is <a href="https://medium.com/@anastasiiasmirnova/real-world-behind-design-first-vs-code-first-part-1-be3c8f2aba34">here</a>.</p><p>In this article, I’ve gathered some of the guidelines that do help make your API better. But do they really have to do something with Schema first approach? In other words, is it the Schema first approach that makes your API better?</p><h4><strong>Take time for design</strong></h4><p>Once you are in production and customers start using your API, changing an existing contract becomes diffficult. If you made a mistake, you definitely can fix it: create a new API, notify users about the changes, plan possible data migration, plan deprecation policy and all other required activities that usually take lots of time. Rushing into development can seem to be fast and time-efficient at a first glance, but unfortunately, as soon as you find design flaws — paying the price is inevitable.</p><h4><strong>Follow the use cases</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*QCki_u2fpIlgJMzlF5rvIA.png" /><figcaption>Collaborating on API with stakeholders is crucial.</figcaption></figure><p>Collaborate on use cases with stakeholders, thus you’ll have an API that covers specific scenarios. Otherwise you might end up with a bunch of endpoints, part of which won’t be used and others will need to be stitched together somehow by your users.</p><h4><strong>Document</strong></h4><p>Having a well documented API is beneficial to you in the first place, as it:</p><ul><li>attracts more customers;</li><li>requires less support;</li><li>helps new developers understand the system.</li></ul><h4><strong>Prototype and iterate</strong></h4><p>You can prototype an API in OpenApi schema as well as in code. Written API code does not imply full implementation. The main idea is that you need to have several rounds of: discussion, implementation, review. So, it’s up to you to decide whether all participants are comfortable with writing/reviewing OpenApi schema or code in specific language.</p><p>Here is an example of how the same endpoint declaration looks like in different representations:</p><p><em>OpenApi schema</em></p><pre>openapi: &quot;3.0.1&quot;<br>info:<br>  title: &quot;Tenant Api Key Api&quot;<br>  version: &quot;0.0.1.beta&quot;</pre><pre>paths:<br>  /tenant/{tenantKey}/apikey/{keyId}:<br>    delete:<br>      parameters:<br>        - name: &quot;tenantKey&quot;<br>          in: &quot;path&quot;<br>          required: true<br>          schema:<br>            type: &quot;string&quot;<br>        - name: &quot;keyId&quot;<br>          in: &quot;path&quot;<br>          required: true<br>          schema:<br>            type: &quot;string&quot;<br>      responses:<br>        &quot;204&quot;:<br>          description: &quot;No Content&quot;</pre><p><em>Java, Spring Boot</em></p><pre>@DeleteMapping(path = <strong>&quot;/{tenantKey}/apikey/{keyId}&quot;</strong>)<br>@ResponseStatus(HttpStatus.<strong><em>NO_CONTENT</em></strong>)<br><strong>public void </strong>deleteApiKey(<br>                        @PathVariable(<strong>&quot;tenantKey&quot;</strong>) String tenantKey, <br>                        @PathVariable(<strong>&quot;keyId&quot;</strong>) String keyId) {<br>}</pre><p><em>Python, Flask</em></p><pre><a href="http://twitter.com/app">@app</a>.route(<strong>&#39;/tenant/&lt;tenantKey&gt;/apikey/&lt;keyId&gt;&#39;</strong>, methods=[&#39;DELETE&#39;])<br>def profile(tenantKey, keyId):<br>    return &#39;&#39;, http.HTTPStatus.<strong>NO_CONTENT</strong></pre><p>OpenApi schema is definitely the most verbose one and in my opinion not the most intuitive.</p><p>I’ve shared the most crucial things for creating new API:</p><ul><li>Take time for design</li><li>Follow the use cases</li><li>Document</li><li>Prototype and iterate</li></ul><p>None of them has to do with neither code nor schema. It’s the best practices that you either follow or skip. Creating your API in schema file instead of writing the code will not help if you have the old processes for creating APIs. What you will get is the same bad, undocumented, unusable API written in the new and shiny OpenApi file.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccf3b2de0670" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-world behind Schema first vs Code first (Part 1)]]></title>
            <link>https://medium.com/@anastasiiasmirnova/real-world-behind-design-first-vs-code-first-part-1-be3c8f2aba34?source=rss-982ae09f821b------2</link>
            <guid isPermaLink="false">https://medium.com/p/be3c8f2aba34</guid>
            <category><![CDATA[design-first]]></category>
            <category><![CDATA[code-first]]></category>
            <category><![CDATA[open-api]]></category>
            <dc:creator><![CDATA[Anastasiia Smirnova]]></dc:creator>
            <pubDate>Tue, 20 Sep 2022 14:05:21 GMT</pubDate>
            <atom:updated>2022-09-21T16:42:51.395Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are looking into using OpenApi for your API development, you’ve probably seen many articles about which approach you should take — Design first or code first.</p><p>Unfortunately, neither. None of these approaches is usable in a real-world scenario. This is how they are usually presented:</p><h4>Code First approach</h4><p>Get requirements and throw them into the code: only code, no design, no planning, no documentation, no communication with other team members, but still very fast.</p><h4>Schema First approach</h4><p>Get requirements and start designing: spend lots of time thinking about design, planning and collaborating with stakeholders, feedback sessions and discussions with team members, no code, only some standard machine-readable language-agnostic specification, not fast.</p><p>The picture looks black and white to me. The real world is always grey, so you should take the best from both approaches, especially keeping in mind your context — language, frameworks that you use, number of developers, developers&#39; maturity, customers, market, etc.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be3c8f2aba34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create secondary index in Spring Data Aerospike]]></title>
            <link>https://medium.com/aerospike-developer-blog/how-to-create-secondary-index-in-spring-data-aerospike-e19d7e343d7c?source=rss-982ae09f821b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e19d7e343d7c</guid>
            <category><![CDATA[spring-data-aerospike]]></category>
            <category><![CDATA[spring-data]]></category>
            <category><![CDATA[aerospike]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Anastasiia Smirnova]]></dc:creator>
            <pubDate>Sat, 16 Jan 2021 19:03:37 GMT</pubDate>
            <atom:updated>2025-02-06T13:24:54.211Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BH93ze7iUalGElSNLBa_OA.jpeg" /><figcaption>Secondary indexes are on a non-primary key, which allows you to model one-to-many relationships. <a href="https://www.aerospike.com/docs/architecture/secondary-index.html">https://www.aerospike.com/docs/architecture/secondary-index.html</a></figcaption></figure><h4>Some of the information in this article is likely outdated, for the current documentation and usage examples please refer to <a href="https://github.com/aerospike/spring-data-aerospike">Spring Data Aerospike</a>.</h4><p>spring-data-aerospike supports creating secondary indexes in Aerospike out of the box.</p><p>There are two ways to accomplish this task:</p><ol><li>Using AerospikeTemplate createIndex method; or</li><li>Using @Indexed annotation placed over the field in your entity.</li></ol><p>Let’s dive into more details.</p><p><em>Note: Before continuing it is expected that your project has spring-data-aerospike already setup. Please check this </em><a href="https://medium.com/aerospike-developer-blog/how-to-setup-spring-data-aerospike-in-spring-boot-application-afa8bcb59224"><em>guide</em></a><em> to find out how to do it.</em></p><h3>First approach — creating index via AerospikeTemplate</h3><p>In this example we will create an index at startup of the application manually.</p><pre>package com.example.demo.persistence.index;</pre><pre>import com.aerospike.client.query.IndexType;<br>import com.example.demo.persistence.simplecrud.MovieDocument;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.data.aerospike.IndexAlreadyExistsException;<br>import org.springframework.data.aerospike.core.AerospikeTemplate;</pre><pre>@Slf4j<br>@Configuration<br>public class AerospikeIndexConfiguration {</pre><pre>    private static final String INDEX_NAME = &quot;movie-rating-index&quot;;</pre><pre>    @Bean<br>    @ConditionalOnProperty(<br>            value = &quot;aerospike.&quot; + INDEX_NAME + &quot;.create-on-startup&quot;,<br>            havingValue = &quot;true&quot;,<br>            matchIfMissing = true)<br>    public boolean createAerospikeIndex(AerospikeTemplate aerospikeTemplate) {<br>        try {<br>            aerospikeTemplate.createIndex(MovieDocument.class, INDEX_NAME, &quot;rating&quot;, IndexType.NUMERIC);<br>            log.info(&quot;Index {} was successfully created&quot;, INDEX_NAME);<br>        } catch (IndexAlreadyExistsException e) {<br>            log.info(&quot;Index {} already exists, skipped creating&quot;, INDEX_NAME);<br>        }<br>        return true;<br>    }<br>}</pre><h3>Second approach — creating index via @Indexed annotation</h3><p>Place @Indexed annotation over the field that you want to index in your entity and specify required types of the index. This will make spring-data-aerospike to auto-create specified secondary index in Aerospike <strong><em>on startup of your application</em></strong>.</p><p><em>Note:</em><em>@Indexed annotation is not supported for the fields annotated with </em><em>@Id, </em><em>@Expiration or </em><em>@Version annotations.</em></p><pre>package com.example.demo.persistence.index;</pre><pre>import lombok.Value;<br>import org.springframework.data.aerospike.annotation.Indexed;<br>import org.springframework.data.aerospike.mapping.Document;<br>import org.springframework.data.annotation.Id;</pre><pre>import java.util.List;</pre><pre>import static com.aerospike.client.query.IndexCollectionType.DEFAULT;<br>import static com.aerospike.client.query.IndexCollectionType.LIST;<br>import static com.aerospike.client.query.IndexType.NUMERIC;<br>import static com.aerospike.client.query.IndexType.STRING;</pre><pre>@Value<br>@Document<br>public class IndexedDocument {</pre><pre>    @Id<br>    String key;</pre><pre>    @Indexed(type = STRING, collectionType = DEFAULT)<br>    String author;</pre><pre>    @Indexed(type = NUMERIC, collectionType = DEFAULT)<br>    int likes;</pre><pre>    @Indexed(type = NUMERIC, collectionType = LIST)<br>    List&lt;Integer&gt; options;<br>}</pre><h3>Testing</h3><p>Verify indexes were created using the following tests:</p><pre>package com.example.demo;</pre><pre>import com.aerospike.client.AerospikeClient;<br>import com.aerospike.client.Info;<br>import com.aerospike.client.cluster.Node;<br>import org.junit.jupiter.api.Test;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.beans.factory.annotation.Value;</pre><pre>import java.util.Arrays;<br>import java.util.List;<br>import java.util.Map;<br>import java.util.stream.Collectors;</pre><pre>import static org.assertj.core.api.Assertions.assertThat;</pre><pre>public class IndexTests extends DemoApplicationTests {</pre><pre>    @Value(&quot;${embedded.aerospike.namespace}&quot;)<br>    String namespace;</pre><pre>    @Autowired<br>    AerospikeClient client;<br></pre><pre>    @Test<br>    void verifyCustomIndexCreated() {<br>        List&lt;String&gt; existingIndexes = getIndexes(client, namespace);</pre><pre>        assertThat(existingIndexes).contains(&quot;movie-rating-index&quot;);<br>    }</pre><pre>    @Test<br>    void verifyAnnotationBasedIndexesCreated() {<br>        List&lt;String&gt; existingIndexes = getIndexes(client, namespace);</pre><pre>        assertThat(existingIndexes)<br>                .contains(<br>                        &quot;IndexedDocument_author_string_default&quot;,<br>                        &quot;IndexedDocument_likes_numeric_default&quot;,<br>                        &quot;IndexedDocument_options_numeric_list&quot;);<br>    }</pre><pre>    // DO NOT USE THIS CODE IN PRODUCTION<br>    private static List&lt;String&gt; getIndexes(AerospikeClient client, String namespace) {<br>        Node node = client.getNodes()[0];<br>        String response = Info.request(node, &quot;sindex/&quot; + namespace);<br>        return Arrays.stream(response.split(&quot;;&quot;))<br>                .map(info -&gt; {<br>                    Map&lt;String, String&gt; keyValue = Arrays.stream(info.split(&quot;:&quot;))<br>                            .map(part -&gt; {<br>                                String[] kvParts = part.split(&quot;=&quot;);<br>                                return Map.entry(kvParts[0], kvParts[1]);<br>                            })<br>                            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));<br>                    return keyValue.get(&quot;indexname&quot;);<br>                })<br>                .collect(Collectors.toList());<br>    }</pre><pre>}</pre><p>Demo project is located on GitHub — <a href="https://github.com/aerospike-community/spring-data-aerospike-demo">https://github.com/aerospike-community/spring-data-aerospike-demo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e19d7e343d7c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aerospike-developer-blog/how-to-create-secondary-index-in-spring-data-aerospike-e19d7e343d7c">How to create secondary index in Spring Data Aerospike</a> was originally published in <a href="https://medium.com/aerospike-developer-blog">Aerospike Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic error handling in spring-data-aerospike]]></title>
            <link>https://medium.com/aerospike-developer-blog/basic-error-handling-in-spring-data-aerospike-5edd580d77d9?source=rss-982ae09f821b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5edd580d77d9</guid>
            <category><![CDATA[spring-retry]]></category>
            <category><![CDATA[aerospike]]></category>
            <category><![CDATA[spring-data-aerospike]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Anastasiia Smirnova]]></dc:creator>
            <pubDate>Thu, 14 May 2020 18:29:14 GMT</pubDate>
            <atom:updated>2025-02-06T13:25:12.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*Pml9bf1qd-ecMxwUb9kyyw.png" /><figcaption><em>Everything fails all the time. © </em>Werner Vogels</figcaption></figure><h4>Some of the information in this article is likely outdated, for the current documentation and usage examples please refer to <a href="https://github.com/aerospike/spring-data-aerospike">Spring Data Aerospike</a>.</h4><p>Working with external resources may be tricky. There are lots of components that can fail during your call to the resource: network, hardware, operating system, load balancer etc. Some of these errors are transient, meaning there are random failures for a very short period of time. Such type of errors can be easily mitigated by using a proven technique called <em>Retries</em>.</p><p>Implementing simple retries is quite easy, but there is already a nice library for that with all the building blocks for creating reliable retry mechanism — Spring Retry.</p><p><em>Note: Before continuing it is expected that your project has spring-data-aerospike already setup. Please check this </em><a href="https://medium.com/aerospike-developer-blog/how-to-setup-spring-data-aerospike-in-spring-boot-application-afa8bcb59224"><em>guide</em></a><em> to find out how to do it.</em></p><p>We are going to use movies domain to demonstrate retries configuration. Here is a basic document and repository:</p><pre>@Value<br>@Document(collection = &quot;demo-service-movies&quot;)<br>@Builder(toBuilder = true)<br>@AllArgsConstructor<br>public class MovieDocument {<br><br>    @Id<br>    String id;<br><br>    @Field<br>    String name;<br><br>    @Field(&quot;desc&quot;)<br>    String description;<br><br>    @Field<br>    double rating;<br><br>    @Version<br>    @NonFinal<br>    long version;<br>}</pre><pre>public interface MovieRepository extends CrudRepository&lt;MovieDocument, String&gt; {<br>}</pre><p>To add retries into your application add the following dependencies into your <em>pom.xml (</em>spring-boot-starter-aop is required as spring-retry uses Spring Aop internally):</p><pre>&lt;dependencies&gt;<br>        &lt;!-- Other dependencies omitted--&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.retry&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-retry&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-aop&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;</pre><p>Next you will need to specify <em>which</em> operations to retry and <em>when</em>. This can be done via @Retryable annotation. You can check all the available options <a href="https://docs.spring.io/spring-retry/docs/api/current/org/springframework/retry/annotation/Retryable.html">here</a>. In this demo we will cover only the most commonly used:</p><pre>import org.springframework.retry.annotation.Backoff;<br>import org.springframework.retry.annotation.Retryable;</pre><pre>@Retryable( // (1)<br>        include = { // (2)<br>                QueryTimeoutException.class,<br>                TransientDataAccessResourceException.class,<br>                OptimisticLockingFailureException.class<br>        },<br>        maxAttempts = 5, // (3)<br>        backoff = @Backoff( // (4)<br>                delay = 3,<br>                multiplier = 2,<br>                random = true // (5)<br>        )<br>)<br>@RequiredArgsConstructor<br>public class MovieOperations {<br><br>    private final MovieRepository repository;<br>    private final AerospikeTemplate template;<br><br>    public void createMovie(Movie movie) {<br>        try {<br>            template.insert(MovieDocument.builder()<br>                    .id(movie.getName())<br>                    .name(movie.getName())<br>                    .description(movie.getDescription())<br>                    .rating(movie.getRating())<br>                    .version(0L)<br>                    .build());<br>        } catch (DuplicateKeyException e) {<br>            throw new IllegalArgumentException(&quot;Movie with name: &quot; + movie.getName() + &quot; already exists!&quot;);<br>        }<br>    }<br><br>    public void deleteMovie(String name) {<br>        repository.deleteById(name);<br>    }<br><br>    public Optional&lt;Movie&gt; findMovie(String name) {<br>        return repository.findById(name)<br>                .map(this::toMovie);<br>    }<br><br>    public Movie updateMovieRating(String name, double newRating) {<br>        return update(name, existingMovie -&gt;<br>                repository.save(existingMovie.toBuilder().rating(newRating).build()));<br>    }<br><br>    public Movie updateMovieDescription(String name, String newDescription) {<br>        return update(name, existingMovie -&gt;<br>                repository.save(existingMovie.toBuilder().description(newDescription).build()));<br>    }<br><br>    private Movie update(String name, Function&lt;MovieDocument, MovieDocument&gt; updateFunction) {<br>        return repository.findById(name)<br>                .map(updateFunction)<br>                .map(this::toMovie)<br>                .orElseThrow(() -&gt; new IllegalArgumentException(&quot;Movie with name: &quot; + name + &quot; not found&quot;));<br>    }<br><br>    private Movie toMovie(MovieDocument doc) {<br>        return new Movie(doc.getName(), doc.getDescription(), doc.getRating());<br>    }<br>}</pre><p>@Retryable explained:</p><ol><li>@Retryable specifies that <em>all</em> the methods in MovieOperations class will be retried when exceptions specified in include field occur. Note that if you place @Retryable annotation over one method — only this method will be retried.</li><li>include specifies exception types that should be retried.</li><li>maxAttempts specifies number of max attempts of retries.</li><li>backoff specifies backoff configuration for the retries.</li><li>random = true enables jitter in backoff timeouts.</li></ol><p>To enable spring-retry you need to add @EnableRetry either into existing configuration class or create a separate class e.g.AerospikeRetryConfiguration:</p><pre>import org.springframework.context.annotation.Configuration;<br>import org.springframework.retry.annotation.EnableRetry;</pre><pre>@EnableRetry<br>@Configuration<br>public class AerospikeRetryConfiguration {</pre><pre>}</pre><p>Demo project is located on GitHub — <a href="https://github.com/aerospike-community/spring-data-aerospike-demo">https://github.com/aerospike-community/spring-data-aerospike-demo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5edd580d77d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aerospike-developer-blog/basic-error-handling-in-spring-data-aerospike-5edd580d77d9">Basic error handling in spring-data-aerospike</a> was originally published in <a href="https://medium.com/aerospike-developer-blog">Aerospike Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to setup spring-data-aerospike in Spring Boot application]]></title>
            <link>https://medium.com/aerospike-developer-blog/how-to-setup-spring-data-aerospike-in-spring-boot-application-afa8bcb59224?source=rss-982ae09f821b------2</link>
            <guid isPermaLink="false">https://medium.com/p/afa8bcb59224</guid>
            <category><![CDATA[spring-data-aerospike]]></category>
            <category><![CDATA[spring-data]]></category>
            <category><![CDATA[aerospike]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Anastasiia Smirnova]]></dc:creator>
            <pubDate>Fri, 24 Apr 2020 19:55:05 GMT</pubDate>
            <atom:updated>2020-04-24T19:55:05.095Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9g3BqgRKFyEl5wFS6vGdSA.png" /></figure><h3>Setting up the project</h3><p>In this section we’ll cover setup of the project from the start.</p><p>First, we’ll need to setup the basic project structure. You can do it either manually if you are familiar with the process or do it via <a href="https://start.spring.io/">Spring Initializr</a>.</p><p>In Spring Initializr you’ll need to select:</p><ul><li>Project: <a href="https://stackoverflow.com/a/13335439/688926">Maven</a> project</li><li>Language: Java</li><li><a href="https://spring.io/projects/spring-boot">Spring Boot</a>: 2.2</li><li>Java: 11</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5r1li8j5ZrfkgzFS.png" /></figure><p>Press <em>Generate</em> button in the bottom of the page and you’ll get zip with initial project. Import project into your favorite IDE and run the test. It should be green and that means that you are ready to continue to the next section.</p><h3>Adding spring-data-aerospike dependency</h3><h4>Note</h4><p>spring-data-aerospike is a Community project and the dependency is not managed by Spring, it has it’s own release cycle and is not included into Spring Boot dependency management. Available versions can be checked on <a href="https://mvnrepository.com/artifact/com.aerospike/spring-data-aerospike">Maven Central</a>.</p><p><a href="https://github.com/aerospike-community/spring-data-aerospike#spring-boot-compatibility">Spring Boot compatibility</a> can be checked for the version of spring-data-aerospike that is compatible with the specific Spring Boot version.</p><p>We are going to use spring-data-aerospike 2.3.3.RELEASE as we have Spring Boot 2.2:</p><p>pom.xml</p><pre>&lt;dependencies&gt;<br>    &lt;!-- Other dependencies omitted--&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;com.aerospike&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-data-aerospike&lt;/artifactId&gt;<br>            &lt;version&gt;2.3.3.RELEASE&lt;/version&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;</pre><h3>Creating Aerospike repository</h3><p>We will be using <a href="https://projectlombok.org/">Lombok</a> library to omit the boilerplate code in the entity class. Add lombok into your pom.xml:</p><pre>&lt;dependencies&gt;<br>    &lt;!-- Other dependencies omitted--&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>            &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>            &lt;scope&gt;provided&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;</pre><p>We are going to use the movies domain in this project, so to be able to read and save our movies into Aerospike we will need to create:</p><ol><li>document(entity) class that represents our domain model,</li><li>repository class that provides <a href="https://en.wikipedia.org/wiki/CRUD">CRUD</a> operations.</li></ol><p>Movie document class will look the following way:</p><pre>@Value // (1)<br>@Document(collection = &quot;demo-service-movies&quot;) // (2)<br>@Builder(toBuilder = true) // (3)<br>@AllArgsConstructor // (4)<br>public class MovieDocument {</pre><pre>    @Id // (5)<br>    String id;</pre><pre>    @Field // (6)<br>    String name;</pre><pre>    @Field(&quot;desc&quot;) // (7)<br>    String description;</pre><pre>    @Field<br>    double rating;</pre><pre>    @Version // (8)<br>    @NonFinal<br>    long version;<br>}</pre><p>Document explained:</p><ol><li><a href="https://projectlombok.org/features/Value">@Value</a> makes class immutable, all fields are made private and final, toString(), equals(), hashCode(), field getters and all args constructor are generated.</li><li>@Document(collection = &quot;demo-service-movies&quot;) marks a class as an entity to be persisted to Aerospike. It also allows to specify set name, expiration and touch on read values. In current example custom set name is specified via collection. Please note that a set name cannot contain the &#39;:&#39; or &#39;;&#39; characters. (See more <a href="https://www.aerospike.com/docs/guide/limitations.html">limitations</a>)</li><li>@Builder provides Builder API for a class.</li><li>@AllArgsConstructor creates public all-args constructor for a class (which is hidden by @Builder). Spring Data can use all-args constructor instead of reflection to <a href="https://docs.spring.io/spring-data/data-commons/docs/current/reference/html/#mapping.object-creation">gain performance boost</a> for object creation.</li><li>@Id marks a field as the primary key.</li><li>@Field is optional, can be set just for the clarity purpose.</li><li>@Field(&quot;desc&quot;) configures the name of a field to be used when persisting the document. This value will be used as a bin name instead of the original field name.</li><li>@Version enables optimistic locking, so that concurrent updates are not lost when saving an entity. <strong>Note</strong> that if concurrent update fails — OptimisticLockingFailureException is thrown.</li></ol><h4>Note</h4><p>Aerospike has <a href="https://www.aerospike.com/docs/guide/limitations.html">limitation</a> on the bin name length. If your document contains field with name that exceeds this limit, specify short name in @Field annotation:</p><pre>@Field(&quot;shortName&quot;)<br>String veryLoooongFieldName;</pre><p>Create Movie Repository interface:</p><pre>public interface MovieRepository extends CrudRepository&lt;MovieDocument, String&gt; { // (1)<br>}</pre><p>Repository explained:</p><ol><li>CrudRepository provides sophisticated CRUD functionality for the entity class.</li></ol><h3>Configuring connection to Aerospike</h3><p>To configure connection to Aerospike you’ll need to create configuration class that extends AbstractAerospikeDataConfiguration. Basic setup requires getHosts() and namespace() methods to be implemented, but you can also override e.g. getClientPolicy() to specify custom configuration for the Aerospike client, or customConverters() to add custom converters.</p><p>We are going to use <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-typesafe-configuration-properties">@ConfigurationProperties</a> for binding Aerospike configuration properties to POJO. Since connection parameters are required, configuration needs to be validated. To enable validation add hibernate-validator dependency to pom.xml:</p><pre>&lt;dependencies&gt;<br>    &lt;!-- Other dependencies omitted --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.hibernate.validator&lt;/groupId&gt;<br>            &lt;artifactId&gt;hibernate-validator&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;</pre><p>Simple configuration will look the following way:</p><pre>@EnableAerospikeRepositories(basePackageClasses = MovieRepository.class)<br>@EnableConfigurationProperties(AerospikeConfiguration.AerospikeConfigurationProperties.class)<br>@Configuration<br>public class AerospikeConfiguration extends AbstractAerospikeDataConfiguration {</pre><pre>    @Autowired<br>    private AerospikeConfigurationProperties properties;</pre><pre>    @Override<br>    protected Collection&lt;Host&gt; getHosts() {<br>        return Host.parseServiceHosts(properties.getHosts());<br>    }</pre><pre>    @Override<br>    protected String namespace() {<br>        return properties.getNamespace();<br>    }</pre><pre>    @Data<br>    @Validated // add this annotation if you want @ConfigurationProperties to be validated!<br>    @ConfigurationProperties(&quot;aerospike&quot;)<br>    public static class AerospikeConfigurationProperties {</pre><pre>        @NotEmpty<br>        String hosts;</pre><pre>        @NotEmpty<br>        String namespace;<br>    }<br>}</pre><p>Now when you run contextLoads test you’ll get exception:</p><pre>Caused by: org.springframework.boot.context.properties.bind.validation.BindValidationException: Binding validation errors on aerospike<br>   - Field error in object &#39;aerospike&#39; on field &#39;hosts&#39;: rejected value [null]; ...(message omitted)<br>   - Field error in object &#39;aerospike&#39; on field &#39;namespace&#39;: rejected value [null]; ...(message omitted)</pre><p>This is expected, as Spring was not able to find neither aerospike.hosts nor aerospike.namespace properties. They are required to setup the connection to Aerospike.</p><h3>Testing</h3><p>To fix the test we need a running Aerospike server. For the test purposes you can use <a href="https://github.com/testcontainers/testcontainers-spring-boot">embedded-aerospike</a> library based on <a href="https://github.com/testcontainers">testcontainers</a> .</p><h4>Note</h4><p>spring-cloud-starter is required to be present on classpath. If you are not using Spring Cloud you can add spring-cloud-starter with test scope.</p><pre>&lt;dependencies&gt;<br>        &lt;!-- Other dependencies omitted--&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-cloud-starter&lt;/artifactId&gt;<br>            &lt;version&gt;2.2.1.RELEASE&lt;/version&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>        &lt;!-- <a href="https://mvnrepository.com/artifact/com.playtika.testcontainers/embedded-aerospike">https://mvnrepository.com/artifact/com.playtika.testcontainers/embedded-aerospike</a> --&gt;<br>            &lt;groupId&gt;com.playtika.testcontainers&lt;/groupId&gt;<br>            &lt;artifactId&gt;embedded-aerospike&lt;/artifactId&gt;<br>            &lt;version&gt;1.48&lt;/version&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;dependencies&gt;</pre><p>This will setup Aerospike container when the test starts.</p><p>Add Aerospike configuration to the test resources (e.g. /test/resources/application.properties):</p><pre>aerospike.hosts=${embedded.aerospike.host}:${embedded.aerospike.port}<br>aerospike.namespace=${embedded.aerospike.namespace}</pre><p>and run the test. It will be green now.</p><p>To verify that the repository is actually working let’s add some basic tests:</p><pre>public class MovieRepositoryTests extends DemoApplicationTests {</pre><pre>    String id;</pre><pre>    MovieDocument movie;</pre><pre>    @Autowired<br>    MovieRepository repository;</pre><pre>    @BeforeEach<br>    void setUp() {<br>        id = UUID.randomUUID().toString();<br>        movie = new MovieDocument(id, &quot;Inception&quot;, &quot;Origin of an idea&quot;, 8.8, 0L);<br>    }</pre><pre>    @Test<br>    public void save_savesMovie() {<br>        repository.save(movie);</pre><pre>        assertThat(repository.findById(id)).hasValue(movie);<br>    }</pre><pre>    @Test<br>    public void exists_returnsTrueIfMovieIsPresent() {<br>        repository.save(movie);</pre><pre>        assertThat(repository.existsById(id)).isTrue();<br>    }</pre><pre>    @Test<br>    public void deleteById_deletesExistingMovie() {<br>        repository.save(movie);</pre><pre>        repository.deleteById(id);</pre><pre>        assertThat(repository.findById(id)).isNotPresent();<br>    }</pre><pre>    @Test<br>    void deleteById_doesNothingForNonexistingMovie() {<br>        repository.deleteById(id);<br>    }<br>}</pre><p>Demo project is located on GitHub — <a href="https://github.com/aerospike-community/spring-data-aerospike-demo">https://github.com/aerospike-community/spring-data-aerospike-demo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afa8bcb59224" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aerospike-developer-blog/how-to-setup-spring-data-aerospike-in-spring-boot-application-afa8bcb59224">How to setup spring-data-aerospike in Spring Boot application</a> was originally published in <a href="https://medium.com/aerospike-developer-blog">Aerospike Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>