<?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 Anil Senocak on Medium]]></title>
        <description><![CDATA[Stories by Anil Senocak on Medium]]></description>
        <link>https://medium.com/@anil.senocak?source=rss-53be7dd28340------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Anil Senocak on Medium</title>
            <link>https://medium.com/@anil.senocak?source=rss-53be7dd28340------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:28:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anil.senocak/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[From OpenAPI to GraphQL Gateway with Spring Boot]]></title>
            <link>https://medium.com/turkcell/from-openapi-to-graphql-gateway-with-spring-boot-d599e36fffc2?source=rss-53be7dd28340------2</link>
            <guid isPermaLink="false">https://medium.com/p/d599e36fffc2</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[open-api]]></category>
            <dc:creator><![CDATA[Anil Senocak]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 10:31:40 GMT</pubDate>
            <atom:updated>2026-10-15T06:36:39.240Z</atom:updated>
            <content:encoded><![CDATA[<p>How OpenAPI documents can drive schema generation and route GraphQL requests without a handwritten resolver for every endpoint.</p><p><a href="https://github.com/senocak/Graphql-Openapi-Apigw">GitHub - senocak/Graphql-Openapi-Apigw: Graphql Openapi Apigw</a></p><p>Working with several REST APIs often means learning several sets of paths, request shapes, and response formats. I wanted one GraphQL endpoint that could present those APIs through a consistent interface while keeping each backend independently configurable. The result is a Spring Boot gateway that uses OpenAPI documents as its contract and generates its GraphQL schema at startup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EmpRrM7TUGA28r5ZV1EuVw.png" /></figure><h4>OpenAPI drives the schema</h4><p>Each API spec has a name, document location, backend base URL, and output path for its generated SDL. The gateway loads the configured specs, generates a schema for each one, and writes those schemas to disk so they’re easy to inspect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_PN51gZDKztofL9Vqywh3Q.png" /></figure><p>For the running application, it combines the generated operations into one schema in memory and serves them through POST /graphql. The merged schema doesn’t need to be saved as a separate file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T29dz7Gz0TdtN2Wx2wwtqA.png" /></figure><p>The flow looks like this: Startup: OpenAPI documents → GraphQL schemas → per-spec SDL files ↘ merged schema in memory</p><p>Request: GraphQL field → operation metadata → REST request → backend response</p><p>A service name helps distinguish operations from different specs. For example, an operation from the auth spec might become authGetUserInfo, while one from the customer spec might become <em>getCustomerList</em>.</p><h4>One resolver interprets operation metadata</h4><p>The gateway doesn’t generate a Java resolver class for every REST endpoint. Instead, the schema generator records metadata such as the HTTP method, route, arguments, request format, and response type. A generic resolver uses that metadata when a GraphQL field is called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JNBFisFXH4S5jG9lMBWUdg.png" /></figure><p>A generated GET operation becomes a GraphQL query. Write operations such as POST, PUT, PATCH, and DELETE become mutations. Path arguments fill route placeholders; query and header arguments are forwarded to their corresponding REST locations. JSON and multipart request bodies are mapped from the OpenAPI definition.</p><p>This keeps the Java implementation small as the number of backend operations grows. Adding an operation usually means updating its OpenAPI document or configuration, rather than writing another resolver.</p><h4>GraphQL names have different jobs</h4><p>A GraphQL operation can have a client-chosen operation name:</p><pre>query GetCustomerListRequest {<br>    getCustomerList {<br>        resultCode<br>        resultName<br>    }<br>}</pre><p>CustomerGetCustomerListRequest is a label useful for logs and for documents containing multiple operations. The field, getCustomerList, is what selects the generated resolver and its REST route. That distinction helped make debugging clearer: the operation name describes the client’s request, while the schema field connects it to the backend operation.</p><h4>Headers and bodyless endpoints</h4><p>The gateway forwards configured inbound headers, including Authorization, so callers can pass their bearer token through to a backend. The gateway doesn’t create or validate that token itself.</p><p>The OpenAPI contract also determines whether a GraphQL field accepts an input body. For a bodyless login operation, the GraphQL mutation has no input argument:</p><pre>mutation {<br>    authUserLoginAuth {<br>        resultCode<br>        accessToken<br>        refreshToken<br>    }<br>}</pre><p>The HTTP request to GraphQL still has its normal JSON envelope containing the query. The gateway’s REST call to the backend has no body and carries the forwarded authorization header.</p><h4>Errors and debugging</h4><p>At startup, the gateway logs the generated GraphQL-to-REST mappings, and the per-spec SDL files show the operation names, routes, and argument mappings. Those artifacts make it possible to inspect what the gateway generated before sending a request.</p><p>For non-successful HTTP responses, the gateway returns a GraphQL error with a status and classification. When the backend provides business details such as resultCode or resultMessage, the gateway can include those details in the error. A business failure returned with a successful HTTP status remains ordinary GraphQL data, so callers can inspect its result fields.</p><p>The main lesson from this project is that generated schemas are only as reliable as their OpenAPI contracts. If a request body or response is described incorrectly, the generated GraphQL API will reflect that. Inspecting the per-spec SDL and comparing it with the REST contract is an important part of development.</p><h4>Running it locally</h4><p>The project uses Maven. Run the tests with:</p><pre>./mvnw test</pre><p>Start the gateway with:</p><pre>./mvnw spring-boot:run</pre><p>At startup, it needs access to each configured OpenAPI document. Once running, clients can send GraphQL operations to /graphql; the gateway translates each selected field into the matching backend REST call.</p><p><a href="https://github.com/senocak/Graphql-Openapi-Apigw">GitHub - senocak/Graphql-Openapi-Apigw: Graphql Openapi Apigw</a></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d599e36fffc2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/turkcell/from-openapi-to-graphql-gateway-with-spring-boot-d599e36fffc2">From OpenAPI to GraphQL Gateway with Spring Boot</a> was originally published in <a href="https://medium.com/turkcell">turkcell</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Session Etcd]]></title>
            <link>https://medium.com/turkcell/spring-session-etcd-dd41074f3d03?source=rss-53be7dd28340------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd41074f3d03</guid>
            <category><![CDATA[spring-session]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[sessions]]></category>
            <category><![CDATA[etcd]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Anil Senocak]]></dc:creator>
            <pubDate>Wed, 09 Sep 2026 07:11:07 GMT</pubDate>
            <atom:updated>2026-09-16T06:11:38.884Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7lEaF9SLYT-KjDWKDaQ9Kg.png" /></figure><p>spring-session-etcd provides an etcd v3-backed Spring Session repository. It moves HTTP session state out of an application&#39;s local memory and stores it as JSON values in etcd, where every application instance can access it.</p><p><a href="https://github.com/senocak/spring-session-etcd">GitHub - senocak/spring-session-etcd</a></p><h4>What is etcd?</h4><p><em>Etcd</em> is an open-source, strongly consistent, distributed key-value store designed to safely save critical data, configuration details, and metadata for computer clusters. Its name combines the Unix system folder <em>/etc</em> with the letter <em>d</em> for distributed. It serves as the core database for <em>Kubernetes</em> to track cluster state.</p><h4>The problem this library solves</h4><p>Most servlet containers keep HttpSession data in the memory of one application process. That is convenient for local development, but it breaks down in common deployment scenarios:</p><ul><li>Restarting the application signs every user out because its in-memory sessions are lost.</li><li>A load balancer can send a user’s next request to a different instance, where that session does not exist.</li><li>Horizontal scaling requires sticky sessions, session replication, or a shared session store.</li><li>Session expiry must be cleaned up independently on every instance.</li></ul><p>Spring Session solves this at the application boundary by routing HttpSession operations through a SessionRepository. This project supplies the missing etcd implementation of that repository. It lets teams that already operate an etcd cluster reuse it for web-session storage instead of introducing Redis or a relational session database solely for that purpose.</p><h4>Why spring-session-etcd matters</h4><p>With this library, session state becomes independent of an individual application instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XI2R-3d5dawaAUmxCnZuMg.png" /></figure><p>The result is a small Spring Session integration with no application-specific etcd code. Existing controllers and Spring Security configuration continue to use the normal HttpSession APIs.</p><h4>How it works</h4><p>Each session is stored at:</p><pre>&lt;namespace&gt;/sessions/&lt;session-id&gt;</pre><p>On every save, the repository attaches an etcd lease for the remaining inactive interval. etcd then removes expired sessions without a local cleanup job. A negative inactive interval creates a persistent session key, and Spring Security session-id rotation removes the old key before saving the replacement.</p><p>Session attributes are serialized as JSON with Jackson 3 and Spring Security’s Jackson modules. This supports common security objects, such as an authenticated principal, as well as ordinary application attributes.</p><h4>Comparison with other Spring Session backends</h4><p>Spring Session applications keep the same HttpSession programming model regardless of the storage backend. The practical differences are operational: which service you already run, what throughput you need, how expiry is handled, and which repository features are required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YlRy1SqM2QRsVspzdgwsBA.png" /></figure><h4>etcd versus redis</h4><p>spring-session-data-redis is usually the first choice for a new, high-throughput session store. Redis is designed for low-latency caching and its Spring Session module has a long production history.</p><p>Choose this library instead when etcd is already a supported dependency in your platform and session volume is modest. It avoids operating Redis solely for sessions, uses etcd’s native leases for expiry, and keeps session records strongly consistent. It is not intended to make etcd a replacement for Redis as a general cache.</p><h4>etcd versus jdbc</h4><p>JDBC is a strong fit when an application already has a managed relational database and does not need another datastore. It is generally easier for teams that prefer SQL backups, auditing, and database tooling.</p><p>etcd is a better fit when the platform already runs an etcd cluster and the session store should be independent of the application’s business database. Its leases also mean expired session keys are removed by etcd itself rather than by a database cleanup schedule.</p><h4>Feature boundary</h4><p>This project implements Spring Session’s core SessionRepository contract. It does not currently provide an indexed session repository, so features such as finding every session for a principal are not available. If that capability is important, evaluate an official backend whose repository supports the required index operations.</p><h4>Switching backends</h4><p>Your controllers and Spring Security code do not need to change when switching Spring Session backends. The stored session formats are backend-specific, however, so plan a cutover that expires or invalidates old sessions and lets users establish new ones.</p><h4>When to use it</h4><p>Use this library when:</p><ul><li>Your application runs more than one instance and needs shared Spring sessions.</li><li>You already run etcd or have it available as supported infrastructure.</li><li>You want etcd-managed TTL cleanup for session records.</li><li>You need a custom Spring Session backend but want to keep the standard Spring Session programming model.</li></ul><p>Prefer another backend when:</p><ul><li>You do not operate etcd and Redis or JDBC is already the simpler operational choice.</li><li>Sessions are very large or have exceptionally high write throughput; etcd is a coordination/key-value store, not a general-purpose cache.</li><li>You need Spring Session features that require an indexed repository, such as lookups by principal name. This library currently implements SessionRepository.</li></ul><h4>Quick start</h4><p>Build and install the library:</p><pre>mvn -f library/pom.xml clean install</pre><p>Add the dependency:</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;com.github.senocak&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-session-etcd&lt;/artifactId&gt;<br>  &lt;version&gt;0.0.1&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Enable etcd-backed HTTP sessions:</p><pre>@Configuration<br>@EnableEtcdHttpSession(<br>    maxInactiveIntervalInSeconds = 1800,<br>    endpoints = &quot;${app.session.etcd.endpoints:http://localhost:2379}&quot;,<br>    namespace = &quot;${app.session.etcd.namespace:spring-session/my-app}&quot;<br>)<br>class SessionConfiguration {}</pre><h4>Example</h4><p>The example uses the etcd profile by default and connects to <a href="http://localhost:2379.">http://localhost:2379.</a></p><pre>docker compose up -d<br>mvn -f library/pom.xml clean install<br>mvn -f example/pom.xml spring-boot:run</pre><p>Run the tests with:</p><pre>mvn -f library/pom.xml test<br>mvn -f example/pom.xml test</pre><h4>Summary</h4><p>spring-session-etcd makes standard Spring HttpSession state available to every application instance through a shared etcd v3 store. It preserves familiar Spring Security and servlet-session APIs while etcd leases handle session expiry. It is a good fit for modest session workloads on platforms that already operate etcd and do not need indexed session lookups.</p><h4>Final</h4><p>Choose a session backend based on the infrastructure and features your application needs. Redis remains the usual choice for a dedicated, high-throughput session store, and JDBC is often simplest when a relational database is already the operational standard. When etcd is the platform’s established distributed key-value store, this library provides a focused way to use it for Spring Session without adding a second datastore just for HTTP sessions.</p><p>Keep sessions small, configure etcd authentication and TLS in production, and plan backend migrations as a session reset because stored formats are not interchangeable.</p><p><a href="https://github.com/senocak/spring-session-etcd">GitHub - senocak/spring-session-etcd</a></p><p><em>Happy Coding!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd41074f3d03" width="1" height="1" alt=""><hr><p><a href="https://medium.com/turkcell/spring-session-etcd-dd41074f3d03">Spring Session Etcd</a> was originally published in <a href="https://medium.com/turkcell">turkcell</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Starter Cache Etcd]]></title>
            <link>https://medium.com/turkcell/spring-boot-starter-cache-etcd-cf57554a72c9?source=rss-53be7dd28340------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf57554a72c9</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[etcd]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Anil Senocak]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 12:02:10 GMT</pubDate>
            <atom:updated>2026-09-01T06:09:32.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BHhGYUlrg4Gvf_sW5ZkDQQ.png" /></figure><p>Default Spring caching setups are often in-memory and process-local. That creates real operational issues in distributed systems:</p><ul><li>cache state is lost on app restart/deploy</li><li>each pod/node has different cache contents</li><li>horizontal scaling reduces cache hit ratio</li><li>stale data is harder to evict globally</li><li>cached data is not inspectable centrally</li></ul><p><a href="https://github.com/senocak/spring-boot-starter-cache-etcd">GitHub - senocak/spring-boot-starter-cache-etcd</a></p><p>This project solves that by persisting cache entries in etcd, so cache state can survive restarts and be shared across multiple app instances. It keeps Spring Cache ergonomics (@Cacheable, @CachePut, @CacheEvict) while moving cache state out of process memory and into a shared, strongly consistent key-value store.</p><p>Use this when:</p><ul><li>you already operate etcd reliably (for example, you run Kubernetes)</li><li>you need persistent/shared cache state</li><li>you want to keep Spring Cache annotations</li><li>you want TTL enforced by the datastore rather than by your application</li></ul><h3>Architecture and data model</h3><h4>Request flow</h4><p>Spring Cache API → EtcdCacheManager → EtcdBackedSpringCache → EtcdCacheImpl → EtcdCacheDocumentStore → etcd</p><h4>Key layout</h4><p>Each cache entry is one etcd key:</p><pre>{keyPrefix}/{cacheName}/{sha256(cacheKey)}   -&gt;   JSON(CacheDocument)</pre><p>The default prefix is /spring_cache_entries (EtcdCacheImpl.DEFAULT_KEY_PREFIX). Hashing the cache key keeps arbitrary key payloads safe to embed in an etcd key path, and makes writes naturally idempotent for the same key. Grouping by cache name means listing one cache is a single prefix scan.</p><h4>Stored document shape</h4><ul><li>cacheName: logical cache bucket</li><li>cacheKey: serialized key used for lookup</li><li>keyJson: serialized original key payload</li><li>valueJson: serialized value payload</li></ul><p>The etcd key holds only a <em>hash</em> of the cache key, so the document still carries the real key so that keys() can reconstruct it. There is no expiresAt field - see below.</p><h3>Expiration model</h3><h4>TTL behavior</h4><p>TTL is delegated entirely to <strong>etcd leases</strong>. On every write the store grants a lease and attaches it to the key, so etcd reclaims the entry server-side with no cooperation from the application.</p><ul><li>entryTtl == null or 0 writes the key without a lease, so it is never reclaimed</li><li>a positive entryTtl grants a lease of that length</li><li><strong>etcd grants leases in whole seconds</strong>, so any sub-second TTL is rounded up to one second</li><li>lease revocation is asynchronous, so a key can briefly outlive its nominal TTL</li></ul><h4>What this means in practice</h4><ul><li>There is <strong>no background scheduler</strong> and no clear-interval. Nothing needs to sweep expired entries.</li><li>Expiry works even if every application instance is down.</li><li><strong>No </strong><strong>CacheEvictedEvent is published when an entry expires.</strong> By the time the TTL elapses the key is already gone from etcd, so there is no value left to put in the event. Events are still published for explicit evict and clear.</li></ul><p>If you need an event on expiry, watch the key prefix with etcd’s native watch API instead of relying on the cache layer.</p><h4>Consistency and concurrency characteristics</h4><ul><li>etcd is strongly consistent, so a successful write is immediately visible to every client.</li><li>Each cache instance uses an internal lock around read-modify-write paths.</li><li>Multi-instance behavior is last-write-wins per key (deterministic key overwrite).</li><li>Eviction events are emitted by the caller instance performing the eviction.</li></ul><h4>Performance considerations</h4><ul><li>This is a remote persistent cache, not an in-memory O(1) local map.</li><li>size, keys, and clear are prefix scans over the cache&#39;s key range.</li><li>clear deletes one key at a time so it can emit a CacheEvictedEvent per entry. A single ranged prefix delete would be cheaper if you do not need those events.</li><li>Every write with a TTL costs an extra round trip for the lease grant.</li><li>etcd is designed for coordination metadata, not bulk storage. Keep values small, watch the default 1.5 MiB request limit, and do not treat it as a general-purpose blob cache.</li><li>Good fit for shared-state correctness and operational simplicity; not ideal for ultra-low-latency hot paths.</li></ul><h3>Comparison with Redis and in-memory cache</h3><h4>Quick comparison</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3YjnZe4dxNhZ4qc0QeB6Gw.png" /></figure><h4>How to choose</h4><ul><li>Choose <strong>in-memory</strong> when single-instance locality and lowest latency matter most.</li><li>Choose <strong>Redis</strong> when you need distributed caching with high throughput, very low latency, or large data volumes.</li><li>Choose this<strong> etcd-backed cache</strong> when you need Spring-cache-friendly persistence with strong consistency, and you are caching a modest amount of data on infrastructure you already run.</li></ul><h4>Important note</h4><p>This project is not intended to replace Redis for extreme hot-path caching or for large datasets. etcd is a coordination store; it targets workloads where consistency and operability matter more than throughput and capacity.</p><h4>Recommended architecture patterns</h4><p><strong>1) Two-level cache (L1 + L2)</strong></p><ul><li><strong>L1 (local memory)</strong>: use a very short-lived in-memory cache (for example Caffeine) for hottest reads.</li><li><strong>L2 (this project)</strong>: use the etcd-backed cache as shared persistent cache across instances.</li><li><strong>Typical flow</strong>: request → L1 miss → L2 lookup → source of truth (DB/API) → populate L2 and L1.</li><li><strong>When to use</strong>: high read traffic where you need lower median latency without losing shared persisted cache behavior.</li></ul><p><strong>2) Write-through service methods</strong></p><ul><li>Use @CachePut on write/update operations so cache state is updated in the same service flow as the source-of-truth write.</li><li>Use @CacheEvict on delete/invalidate operations to keep cache and source aligned.</li><li>Best for straightforward CRUD services with predictable cache keys.</li></ul><p><strong>3) Lease-driven freshness</strong></p><ul><li>Set entry-ttl to the business freshness requirement and let etcd handle the rest - no scheduler to configure or tune.</li><li>Remember the whole-second granularity: a TTL below one second is not expressible.</li><li>Best when stale reads are acceptable only inside a bounded TTL window.</li></ul><p><strong>4) Event-observed caching</strong></p><ul><li>Subscribe to CacheInsertedEvent and CacheEvictedEvent for observability and audit-style logging.</li><li>Use emitted events to track churn and identify noisy keys — but remember expiry is silent, so these events cover explicit writes and evictions only.</li></ul><h4>Direct usage</h4><pre>EtcdCacheImpl&lt;String, User&gt; cache = new EtcdCacheImpl&lt;&gt;(<br>    &quot;users&quot;,<br>    String.class,<br>    User.class,<br>    etcdClient,<br>    &quot;/spring_cache_entries&quot;,<br>    EtcdCacheImpl.defaultObjectMapper(),<br>    applicationEventPublisher,<br>    Duration.ofMinutes(10)<br>);<br><br>cache.put(&quot;user-1&quot;, user);<br>User cached = cache.get(&quot;user-1&quot;);</pre><h4>Spring Cache usage</h4><pre>@Configuration<br>@EnableCaching<br>class CacheConfig {<br>    @Bean(destroyMethod = &quot;close&quot;)<br>    Client etcdClient() {<br>        return Client.builder().endpoints(&quot;http://localhost:2379&quot;).build();<br>    }<br><br>    @Bean(&quot;etcdCacheManager&quot;)<br>    CacheManager cacheManager(<br>        Client etcdClient,<br>        ObjectMapper objectMapper,<br>        ApplicationEventPublisher publisher<br>    ) {<br>        return new EtcdCacheManager(<br>            etcdClient,<br>            &quot;/spring_cache_entries&quot;,<br>            objectMapper,<br>            Object::toString,<br>            publisher,<br>            Duration.ofMinutes(10)<br>        );<br>    }<br>}</pre><p>Use standard Spring annotations:</p><pre>@Cacheable(value = &quot;usersByUsername&quot;, key = &quot;#username&quot;, cacheManager = &quot;etcdCacheManager&quot;)<br>public User getUserByUsername(String username) { /* ... */ }<br><br>@CachePut(value = &quot;users&quot;, key = &quot;#result.id&quot;, cacheManager = &quot;etcdCacheManager&quot;)<br>public User createUser(CreateUserRequest request) { /* ... */ }<br><br>@CacheEvict(value = &quot;users&quot;, key = &quot;#userId&quot;, cacheManager = &quot;etcdCacheManager&quot;)<br>public boolean deleteUser(String userId) { /* ... */ }</pre><blockquote><strong><em>Pass your own </em></strong><strong><em>ObjectMapper.</em></strong><em> </em><em>EtcdCacheImpl.defaultObjectMapper() is a plain Jackson mapper with </em><em>JavaTimeModule only. Cached types that need extra modules - Kotlin data classes in particular - fail to deserialize unless you hand in the application&#39;s configured mapper, as the example above does.</em></blockquote><h4>Configuration</h4><p>example/src/main/resources/application.yml:</p><pre>spring:<br>  etcd:<br>    endpoints: http://localhost:2379<br>    cache:<br>      key-prefix: /spring_cache_entries<br>      entry-ttl: 30s</pre><h4>Config notes</h4><ul><li>endpoints: comma-separated etcd client URLs</li><li>key-prefix: etcd key namespace holding all cache entries</li><li>entry-ttl: per-entry lease lifetime; omit or set 0 for entries that never expire</li></ul><p>Optional spring.etcd.user, spring.etcd.password, and spring.etcd.namespace are also bound by the example&#39;s EtcdProperties.</p><p>There is deliberately no clear-interval - etcd reclaims expired entries itself.</p><h4>Events</h4><p>The cache can publish:</p><ul><li>CacheInsertedEvent</li><li>CacheEvictedEvent</li></ul><p>These events are published after successful operations by the cache layer. Expiry is handled by etcd and does <strong>not</strong> produce an event.</p><h4>Build and test</h4><p>Run library tests (no Docker needed — they run against an in-memory store double):</p><pre>mvn -f library/pom.xml test</pre><p>Install the library so the example module can resolve it:</p><pre>mvn -f library/pom.xml install</pre><p>Run example tests (requires Docker):</p><pre>mvn -f example/pom.xml test</pre><p>The example integration tests start a real single-node etcd through io.etcd:jetcd-launcher, the official jetcd Testcontainers helper. The container is shared across test classes within one Maven/JVM run, and each test class uses a unique key-prefix so the suites cannot collide.</p><p>EtcdLeaseTtlIntegrationTest is the only place lease expiry is verified. Because etcd leases are whole seconds, it uses a 2s TTL and polls for reclamation rather than sleeping a fixed span.</p><p>Build example app:</p><pre>mvn -f example/pom.xml -Dmaven.test.skip=true package</pre><h4>Running locally</h4><pre>docker compose up -d mvn -f example/pom.xml spring-boot:run</pre><p>This starts etcd on localhost:2379 plus an <a href="http://localhost:8081/">etcdv3-browser</a> UI, so you can watch cache keys appear under /spring_cache_entries/ and disappear as their leases expire. Drive the app with example/src/main/resources/etcd.http.</p><h4>Artifact</h4><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.github.senocak&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-cache-etcd&lt;/artifactId&gt;<br>    &lt;version&gt;0.0.4&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p><a href="https://github.com/senocak/spring-boot-starter-cache-etcd">GitHub - senocak/spring-boot-starter-cache-etcd</a></p><p><em>Happy Coding!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf57554a72c9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/turkcell/spring-boot-starter-cache-etcd-cf57554a72c9">Spring Boot Starter Cache Etcd</a> was originally published in <a href="https://medium.com/turkcell">turkcell</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Data Etcd Repository]]></title>
            <link>https://medium.com/turkcell/spring-data-etcd-repository-5e3672581d1e?source=rss-53be7dd28340------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e3672581d1e</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-data]]></category>
            <category><![CDATA[etcd]]></category>
            <dc:creator><![CDATA[Anil Senocak]]></dc:creator>
            <pubDate>Sat, 25 Jul 2026 17:56:38 GMT</pubDate>
            <atom:updated>2026-09-01T06:08:00.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cVY8EwWP4dYNngcSlxqzMA.png" /><figcaption>Spring Data Etcd Repository</figcaption></figure><p><a href="https://github.com/senocak/spring-boot-starter-data-etcd">GitHub - senocak/spring-boot-starter-data-etcd</a></p><p>A <strong>Spring Data</strong> module that lets you talk to <a href="https://etcd.io/">etcd</a>, the distributed strongly-consistent key/value store, using the same Repository pattern you already use for JPA, MongoDB or Redis.</p><p>You declare an interface, annotate a POJO, and get CRUD, derived query methods, secondary indexes, pagination and per-record time-to-live, all backed by etcd.</p><pre>public interface UserRepository extends EtcdRepository&lt;User, String&gt; {<br>    List&lt;User&gt; findAllByAuthor(String author);<br>    Page&lt;User&gt; findAllByTitle(String title, Pageable pageable);<br>}</pre><h4>The problem this solves</h4><p>etcd is everywhere in cloud-native infrastructure, but its Java client( <a href="https://github.com/etcd-io/jetcd">jetcd</a>) is intentionally low-level. To persist a domain object you have to do all of this by hand:</p><ul><li>serialize the object to JSON (or protobuf) yourself,</li><li>design and build a key naming scheme (User:42, User:43, ...),</li><li>wrap every call in CompletableFuture.get() and translate ByteSequence ↔ String,</li><li>implement “find by a non-key field” as a <strong>full keyspace scan</strong> and deserialize everything,</li><li>manage etcd <strong>leases</strong> manually if you want keys to expire,</li><li>keep any secondary lookup structures consistent on every write and delete.</li></ul><p>That is a lot of boilerplate and a lot of easy-to-get-wrong consistency code, repeated in every project. <strong>This library hides all of it behind Spring Data’s repository abstraction.</strong></p><h4>Who needs it</h4><ul><li>Teams already invested in the Spring Data programming model who want etcd as a backing store.</li><li>Apps that already run next to etcd (Kubernetes operators, controllers, config/feature-flag services, service-discovery and leader-election tooling) and would rather not run a second database just to store a handful of domain objects.</li><li>Anyone who wants <strong>TTL-expiring records</strong> (sessions, tokens, ephemeral locks, heartbeats) with native etcd lease semantics, expressed as a single annotation.</li></ul><h4>Features</h4><ul><li>Standard CRUD: Extend EtcdRepository&lt;T, ID&gt; (a CrudRepository)</li><li>Derived query methods: findAllByAuthor, findByAuthorIn, findByActiveTrue, ...</li><li>Secondary indexes: @Indexed on a field → equality queries use a prefix scan, not a full scan</li><li>Time-to-live (expiry): @TimeToLive on a numeric field → etcd lease granted on save, remaining TTL read back</li><li>Spring Boot config: spring.etcd.* properties; KV/ Lease/ ObjectMapper beans auto-created</li></ul><h4>How it works (technical overview)</h4><p>@EnableEtcdRepositories imports EtcdRepositoriesRegistrar, a RepositoryBeanDefinitionRegistrarSupport. It registers an EtcdRepositoryConfigurationExtension (module name <strong>ETCD</strong>, prefix <strong>etcd</strong>) that tells Spring Data to back every interface extending EtcdRepository with an EtcdRepositoryFactoryBean.</p><pre>@EnableEtcdRepositories<br>        │  @Import<br>        ▼<br>EtcdRepositoriesRegistrar ──► EtcdRepositoryConfigurationExtension<br>        │                              (module = &quot;ETCD&quot;)<br>        ▼<br>EtcdRepositoryFactoryBean ──► EtcdRepositoryFactory ──► SimpleEtcdRepository  (the proxy target)<br>                                        │<br>                                        ▼<br>                               EtcdEntityTemplate  ──►  jetcd KV + Lease clients</pre><p>The connection beans ( Client, KV, Lease, ObjectMapper) live in EtcdRepositoryConfiguration, a @Configuration class, and EtcdProperties binds spring.etcd.*. These are discovered by component scanning. See <a href="https://github.com/senocak/spring-boot-starter-data-etcd#project-layout-requirement">Project layout requirement</a>.</p><h4>Key layout in etcd</h4><p>EtcdEntityTemplate maps each entity to a small set of keys:</p><pre>Primary record :  &lt;SimpleClassName&gt;:&lt;id&gt;                       -&gt;  JSON document<br>Secondary index:  idx:&lt;SimpleClassName&gt;:&lt;field&gt;:&lt;value&gt;:&lt;id&gt;   -&gt;  &lt;id&gt;</pre><ul><li>The id type is detected from a Spring Data @Id field, or a field named id as a fallback (EtcdEntityInformation).</li><li>Indexed values are <strong>Base64-url encoded</strong> before being put in the key, so a value can never contain the : delimiter and prefix scans stay unambiguous.</li></ul><h4>Reads, writes and queries</h4><ul><li><strong>save</strong>: serializes to JSON via Jackson, removes any stale index entries for a pre-existing record, writes the primary record, then (re)writes one index entry per @Indexed field. All keys share the same lease (see TTL below).</li><li><strong>findById / findAll:</strong> a point read / prefix scan, deserializing JSON back into your type.</li><li><strong>Derived queries</strong> (EtcdRepositoryFactory): the method name is parsed into a Spring Data PartTree. If the query is a pure AND expression and one condition is an <strong>equality match on an </strong><strong>@Indexed field</strong>, the candidate ids are resolved with a single index prefix scan and only those records are read. Otherwise it falls back to findAll and filters in memory. The full predicate is always applied afterwards, so non-indexed conditions stay correct.</li><li><strong>Pagination/sorting</strong> — handled in memory after candidate resolution; returns Page, Slice, or a plain List depending on the method&#39;s return type.</li></ul><h4>Time-to-live (@TimeToLive)</h4><p>Annotate one numeric field with @TimeToLive(unit = ...):</p><pre>@TimeToLive(unit = TimeUnit.SECONDS)<br>private Long ttl;</pre><ul><li><strong>On save</strong> — if the field holds a positive value, the template grants an etcd <strong>lease</strong> for the equivalent number of seconds (converted from the annotation’s TimeUnit) and attaches that lease to the primary record <strong>and</strong> its index entries. When etcd expires the lease, every key for that record disappears atomically. A null/zero/absent value means <em>no lease</em> - the key never expires (leaseId = 0).</li><li><strong>On read</strong> — if the stored key still carries a lease, the template calls Lease.timeToLive(...) and writes the <strong>remaining</strong> time back into the field (converted to the field&#39;s TimeUnit and numeric type). A lease that no longer exists leaves the field untouched.</li></ul><h4>Limitation</h4><ul><li><strong>Supported query keywords (Redis-style restriction):</strong> etcd has no secondary-query engine, so (exactly like Spring Data Redis) only a small set of derivation keywords is allowed. The set is validated <strong>eagerly, when the repository is created</strong>:</li></ul><blockquote><em>Supported: </em><em>SimpleProperty (equality), </em><em>True, </em><em>False, </em><em>In. Anything else (</em><em>Containing, </em><em>StartingWith, </em><em>EndingWith, </em><em>Like, </em><em>GreaterThan, </em><em>Between, …) throws at startup, with the same message shape Redis produces:</em></blockquote><blockquote><em>java.lang.IllegalArgumentException: CONTAINING (1): [IsContaining, Containing, Contains] is not supported for ETCD query derivation</em></blockquote><ul><li><strong>No range/text query pushdown:</strong> etcd only indexes by key prefix. Non-equality conditions are evaluated in memory after a scan; the keyword whitelist above prevents you from accidentally writing a query that <em>looks</em> like it filters server-side but cannot.</li><li><strong>Pagination and sorting are in-memory:</strong> fine for modest datasets, not for very large keyspaces.</li><li><strong>Index cleanup on delete-by-id.</strong> Deleting through the repository removes the primary record; ensure your delete path also clears index entries when you extend the demo (see the TODO in the example controller).</li><li><strong>Counting</strong> is implemented as findAll().size().</li></ul><h3>Getting started</h3><h4>Run etcd</h4><pre>docker compose up -d        # starts etcd on :2379 and an etcd browser on :8081</pre><h4>Add the dependency</h4><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.github.senocak&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-data-etcd&lt;/artifactId&gt;<br>    &lt;version&gt;0.0.2&lt;/version&gt;<br>&lt;/dependency&gt;</pre><blockquote><em>The library depends on </em><em>spring-tx (compile scope). Spring Data&#39;s repository infrastructure uses </em><em>org.springframework.dao.* exceptions which live in that jar, and </em><em>spring-data-commons only declares it </em>optionally<em> - so the starter pulls it in explicitly. Without it you would see </em><em>NoClassDefFoundError: org/springframework/dao/InvalidDataAccessApiUsageException.</em></blockquote><h4>Configure the connection</h4><pre>spring:<br>  etcd:<br>    host: http://localhost:2379<br>    user: &quot;&quot;        # optional<br>    password: &quot;&quot;    # optional</pre><h4>Enable repositories</h4><pre>@SpringBootApplication<br>@EnableEtcdRepositories<br>public class Application {<br>    public static void main(String[] args) {<br>        SpringApplication.run(Application.class, args);<br>    }<br>}</pre><h4>Project layout requirement</h4><p>The connection beans ( EtcdRepositoryConfiguration, EtcdProperties) are picked up by Spring&#39;s <strong>component scan</strong>, so your @SpringBootApplication class must sit in a package that is a parent of com.github.senocak.etcd.config - or you must @Import(EtcdRepositoryConfiguration.class) and @EnableConfigurationProperties(EtcdProperties.class) explicitly.</p><h4>Define an entity and a repository</h4><pre>public class User {<br>    private String id;                          // id (auto-generated UUID if null on save)<br>    @Indexed private String title;              // indexed -&gt; fast equality queries<br>    @Indexed private String author;<br>    @TimeToLive(unit = TimeUnit.SECONDS)<br>    private Long ttl;                            // record expires after `ttl` seconds<br>    // getters / setters …<br>}<br><br>public interface UserRepository extends EtcdRepository&lt;User, String&gt; {<br>    List&lt;User&gt; findAllByAuthor(String author);              // uses the author index<br>    Page&lt;User&gt;  findAllByTitle(String title, Pageable p);   // indexed + paginated<br>}</pre><pre>User u = new User();<br>u.setTitle(&quot;hello&quot;);<br>u.setAuthor(&quot;ada@example.com&quot;);<br>u.setTtl(60L);                 // disappears from etcd after 60 seconds<br>userRepository.save(u);        // id assigned automatically<br><br>userRepository.findAllByAuthor(&quot;ada@example.com&quot;);<br>userRepository.findById(u.getId());   // returned User has ttl ≈ remaining seconds</pre><p><a href="https://github.com/senocak/spring-boot-starter-data-etcd">GitHub - senocak/spring-boot-starter-data-etcd</a></p><p><em>Happy coding!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e3672581d1e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/turkcell/spring-data-etcd-repository-5e3672581d1e">Spring Data Etcd Repository</a> was originally published in <a href="https://medium.com/turkcell">turkcell</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Column-Level Encryption / Decryption with Oracle `DBMS_CRYPTO` in Spring Boot]]></title>
            <link>https://medium.com/turkcell/column-level-encryption-decryption-with-oracle-dbms-crypto-in-spring-boot-84cf47a2c8fa?source=rss-53be7dd28340------2</link>
            <guid isPermaLink="false">https://medium.com/p/84cf47a2c8fa</guid>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[oracle]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Anil Senocak]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 17:20:46 GMT</pubDate>
            <atom:updated>2026-07-11T17:20:46.641Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Column-Level Encryption / Decryption with Oracle `DBMS_CRYPTO` in Spring Boot" src="https://cdn-images-1.medium.com/max/1024/1*wCq4z6hn1VYwfmvEpKKu5Q.png" /><figcaption>Column-Level Encryption / Decryption with Oracle `DBMS_CRYPTO` in Spring Boot</figcaption></figure><h3>The problem</h3><p>Most “the database is encrypted” stories stop at Transparent Data Encryption (TDE) the datafiles, redo logs, and backups are encrypted on disk, so an attacker who steals the raw .dbf files or a tape backup gets ciphertext. That&#39;s necessary but not sufficient. Once anyone, a DBA, an analyst with read-only access, an attacker who phished a service account, an unauthorized tool that landed a SELECT * query opens a <em>connection</em> to the database, TDE has already decrypted everything for them. The whole &quot;encryption&quot; boundary lives at the storage layer, not at the column.</p><p>For regulated data (national-ID numbers, phone numbers, addresses under KVKK/GDPR; cardholder data under PCI-DSS; PHI under HIPAA), this gap matters: a leak through a legitimate DB connection is the most common breach path, not raw disk theft. The mitigation is column-level encryption the bytes physically stored in the firstname / lastname columns are ciphertext, and decryption only happens when the right key is presented. A DBA running SELECT firstname FROM users sees HEXTORAW(&#39;A8C1...&#39;), not Anıl.</p><p><a href="https://github.com/senocak/Spring-Oracle-Column-Level-Encryption-Decryption">GitHub - senocak/Spring-Oracle-Column-Level-Encryption-Decryption: Spring Oracle Column Level Encryption Decryption</a></p><p>The naive way to do this is to encrypt in the <em>application</em> call a crypto.encrypt(...) helper before every repository.save() and a crypto.decrypt(...) after every findBy*(). This works for trivial CRUD but falls apart fast:</p><ul><li>Every query path has to remember. Native queries, reporting jobs, batch importers, JdbcTemplate one-offs, raw EntityManager.createQuery calls each one is an opportunity to forget the wrapper and either store plaintext or read ciphertext as garbage.</li><li>WHERE / LIKE / ORDER BY break. The database can only compare what it can see. If the column is ciphertext, a LIKE &#39;%anıl%&#39; predicate matches nothing — you either have to pull every row to the app and filter in memory, or build an awkward &quot;encrypt the search term and compare ciphertext&quot; path that only works for exact equality with a deterministic cipher.</li><li>Migrations and ad-hoc fixes hurt. Anyone running a Flyway script or a one-off UPDATE has to know the encryption convention and apply it manually.</li><li>The leak surface is wide. Every Kotlin call site, every test fixture, every seed data loader has to be reviewed. Miss one, and that column ends up half-encrypted forever.</li></ul><h3>The Solution</h3><p>What this project solves: the encryption boundary is pushed <em>down</em> into the database into a pair of SQL functions (encrypt_text / decrypt_text) that are the only point at which plaintext and ciphertext meet. Hibernate&#39;s @ColumnTransformer then makes the application physically unable to bypass them: every query Hibernate generates including JPA Criteria predicates used for LIKE filtering is rewritten at the ORM level to call those functions.</p><p>Application code reads and writes Kotlin String values exactly as if the column were unencrypted; WHERE firstname LIKE &#39;%anıl%&#39; works against the <em>decrypted</em> value because the SQL Hibernate sends is WHERE LOWER(decrypt_text(firstname)) LIKE ?. Backups, exports, replicas, and SELECT * from a DBA&#39;s IDE all see ciphertext. The only way to read plaintext is to be a session that holds the key, and the key never appears in application code at all.</p><p>This project shows how to push column-level encryption <em>into the database</em> while keeping the application code free of any awareness of it. The Spring/Kotlin/JPA layer reads and writes plain Kotlin String values; ciphertext lives only inside the database column, and the encryption/decryption hop happens inside a pair of SQL functions that the database invokes on every read and write.</p><p>The entity declares an encrypt_text(text) / decrypt_text(raw) function pair and wires them into the column via @ColumnTransformer. Hibernate then rewrites every generated query to call those functions automatically.</p><h4>Core idea</h4><p>Hibernate’s @ColumnTransformer lets you inject a SQL expression around a column on read and on write. Anywhere Hibernate would emit SELECT firstname FROM users it instead emits SELECT decrypt_text(firstname) FROM users, and anywhere it would emit INSERT ... VALUES (?) it emits INSERT ... VALUES (encrypt_text(?)). Critically, this applies to <strong>every</strong> Hibernate-generated query - including JPA Criteria queries used for filtering - so a LIKE &#39;%anıl%&#39; on firstname becomes a LIKE on the <em>decrypted</em> value, transparently.</p><p>The entity declaration is the whole contract:</p><pre>@Entity<br>@Table(name = &quot;users&quot;)<br>class User(<br>    @Column(name = &quot;firstname&quot;, nullable = false, columnDefinition = &quot;RAW(2000)&quot;)<br>    @ColumnTransformer(<br>        read  = &quot;decrypt_text(firstname)&quot;,<br>        write = &quot;encrypt_text(?)&quot;<br>    )<br>    var firstname: String,<br><br>    @Column(name = &quot;lastname&quot;, nullable = false, columnDefinition = &quot;RAW(2000)&quot;)<br>    @ColumnTransformer(<br>        read  = &quot;decrypt_text(lastname)&quot;,<br>        write = &quot;encrypt_text(?)&quot;<br>    )<br>    var lastname: String<br>) : BaseDomain()</pre><p>From this point on, the rest of the application ( UserRepository, the /users controller, the JPA Specification that builds LIKE predicates) is written as if firstname and lastname were ordinary VARCHAR columns.</p><h4>How a request flows end-to-end</h4><p>GET /users?firstname=Anıl3&amp;lastname=Senocak3 triggers the following:</p><ul><li><strong>Controller</strong> builds a JPA Specification containing two LIKE predicates against root.get(&quot;firstname&quot;) and root.get(&quot;lastname&quot;).</li><li><strong>Hibernate</strong> plans the query. Because of @ColumnTransformer(read = ...), the projected columns and the predicate columns are rewritten to wrap the raw column in decrypt_text(...). The resulting SQL looks like:</li></ul><pre>SELECT decrypt_text(firstname), decrypt_text(lastname), id, created_at<br>FROM   users<br>WHERE  LOWER(decrypt_text(firstname)) LIKE ?<br>  AND  LOWER(decrypt_text(lastname))  LIKE ?</pre><ul><li><strong>Database</strong> executes decrypt_text per row, compares the result to the bind parameter, returns plaintext over the wire.</li><li><strong>JPA</strong> hydrates User instances with the decrypted strings; Jackson serializes them to JSON.</li></ul><p>Inserts work in mirror image. The init block in CryptoApplication:</p><pre>userRepository.save(User(firstname = &quot;Anıl1&quot;, lastname = &quot;Senocak1&quot;))</pre><p>results in:</p><pre>INSERT INTO users (firstname, lastname, created_at, id)<br>VALUES (encrypt_text(?), encrypt_text(?), ?, ?)</pre><p>The plaintext never lands in the column. At rest, SELECT firstname FROM users returns ciphertext bytes.</p><h4>`DBMS_CRYPTO` setup</h4><p>DBMS_CRYPTO is a builtin Oracle package that exposes primitive cipher operations. Access has to be granted explicitly to the working schema:</p><pre>GRANT EXECUTE ON DBMS_CRYPTO TO your_schema;<br>-- e.g. GRANT EXECUTE ON DBMS_CRYPTO TO SYSTEM;</pre><p>Then define the two wrapper functions the entity expects. AES-128 in CBC mode with PKCS#5 padding is a sane symmetric default. <strong>The 16-byte key below is for demo only</strong> — see <a href="https://github.com/senocak/Spring-Oracle-Column-Level-Encryption-Decryption#key-management">Key management</a> for what a real deployment needs.</p><p>Quick sanity check at the SQL prompt:</p><pre>CREATE OR REPLACE FUNCTION encrypt_text(p_text VARCHAR2)<br>    RETURN RAW<br>AS<br>BEGIN<br>    RETURN DBMS_CRYPTO.ENCRYPT(<br>        src =&gt; UTL_RAW.CAST_TO_RAW(p_text),<br>        typ =&gt; DBMS_CRYPTO.ENCRYPT_AES128<br>             + DBMS_CRYPTO.CHAIN_CBC<br>             + DBMS_CRYPTO.PAD_PKCS5,<br>        key =&gt; UTL_RAW.CAST_TO_RAW(&#39;1234567890123456&#39;)<br>    );<br>END;</pre><pre>CREATE OR REPLACE FUNCTION decrypt_text(p_raw RAW)<br>    RETURN VARCHAR2<br>AS<br>BEGIN<br>    RETURN UTL_RAW.CAST_TO_VARCHAR2(<br>        DBMS_CRYPTO.DECRYPT(<br>            src =&gt; p_raw,<br>            typ =&gt; DBMS_CRYPTO.ENCRYPT_AES128<br>                 + DBMS_CRYPTO.CHAIN_CBC<br>                 + DBMS_CRYPTO.PAD_PKCS5,<br>            key =&gt; UTL_RAW.CAST_TO_RAW(&#39;1234567890123456&#39;)<br>        )<br>    );<br>END;</pre><p>The column type is RAW(2000) (declared via columnDefinition on the entity) because DBMS_CRYPTO.ENCRYPT returns RAW and the ciphertext is binary, not text. 2000 is the maximum inline RAW length in Oracle; for larger payloads, switch to BLOB and adjust the function signatures to BLOB in/out.</p><h4>Cipher choice cheat sheet</h4><p>DBMS_CRYPTO.ENCRYPT takes a typ argument that is the bitwise sum of three constants; algorithm + chaining mode + padding. The combination above is:</p><pre>| Part     | Constant        | Meaning                                                               |<br>|----------|-----------------|-----------------------------------------------------------------------|<br>| Algorithm| `ENCRYPT_AES128`| AES with a 16-byte key. `ENCRYPT_AES192` / `ENCRYPT_AES256` if longer.|<br>| Chaining | `CHAIN_CBC`     | CBC mode. The IV defaults to all zeros — see *Key management* below.  |<br>| Padding  | `PAD_PKCS5`     | PKCS#5/7 padding so arbitrary-length plaintexts encrypt cleanly.      |</pre><h4>Key management</h4><p>The 16-byte literal in encrypt_text(&#39;1234567890123456&#39;) is a placeholder for the demo. For anything real:</p><ul><li>Keys should not live in CREATE FUNCTION source. Use Oracle Wallet / Key Vault, or fetch from a secret manager at session start and stash in a context variable that the functions read from.</li><li>AES-128 CBC with a static key <em>and</em> a static IV (the default-all-zeros IV used here, since no iv argument is passed) produces deterministic ciphertext — the same plaintext encrypts to the same bytes — which leaks equality and enables frequency analysis. If equality search isn&#39;t a requirement, pass a random IV per encryption and store it alongside the ciphertext, or switch to ENCRYPT_AES_GCM for authenticated encryption.</li><li>Rotate keys by re-encrypting columns with a versioned key tag — keep the version byte in the stored ciphertext so decrypt_text can dispatch to the right key.</li></ul><h4>What the integration test verifies</h4><p>CryptoApplicationTests is a @SpringBootTest that drives the live app against a real database and asserts two properties:</p><p><strong>1. Round-trip correctness through JPA.</strong> Save three User rows, read them back via userRepository.findAll(), confirm the strings come back identical to what was written.</p><p><strong>2. Ciphertext at rest.</strong> Bypass Hibernate, issue raw JDBC against the users table, and confirm that the bytes physically stored in the firstname/ lastname columns are <strong>not equal to</strong> the bytes of the plaintext and are <strong>longer</strong> than the plaintext (because of the cipher block padding). This is the check that proves the encryption is real, rather than a no-op stub.</p><p>A third test exercises the Criteria-based /users?firstname=...&amp;lastname=... filter end-to-end, including case-insensitive matching on the <em>decrypted</em> values, proving the read = &quot;decrypt_text(...)&quot; rewrite kicks in for Hibernate-built predicates and not just for fetched columns.</p><h4>Running locally</h4><ul><li>Start Oracle Free (one-time): docker compose up -d. Listens on localhost:1522, service FREEPDB1, system / testpassword. See the comments inside docker-compose.yml for the in-container steps to set the password and create a working schema if you don&#39;t want to use SYSTEM.</li></ul><pre>version: &#39;3.7&#39;<br>services:<br>  oracle-free2:<br>    image: container-registry.oracle.com/database/free:23.9.0.0<br>    restart: unless-stopped<br>    ports:<br>      - &quot;1522:1521&quot;<br>    environment:<br>      - ORACLE_PWD=testpassword</pre><pre>jdbc:oracle:thin:system/testpassword@//localhost:1522/FREEPDB1</pre><pre>SELECT encrypt_text(&#39;hello&#39;) FROM dual; -- → EBB7C703E675DB3DA397038B4C17823C SELECT decrypt_text(&#39;EBB7C703E675DB3DA397038B4C17823C&#39;) FROM dual; -- → hello</pre><ul><li>Connect oracle as sys dba and run:</li></ul><pre>jdbc:oracle:thin:sys/testpassword@//localhost:1522/FREEPDB1?internal_logon=sysdba</pre><p>then execute this to grant the crypto permissions to the SYSTEM user (or your chosen schema):</p><pre>GRANT EXECUTE ON DBMS_CRYPTO TO SYSTEM;</pre><ul><li>Connect as SYSTEM (or your chosen schema) and test it:</li></ul><pre>jdbc:oracle:thin:system/testpassword@//localhost:1522/FREEPDB1</pre><pre>SELECT encrypt_text(&#39;hello&#39;) FROM dual; -- → EBB7C703E675DB3DA397038B4C17823C<br>SELECT decrypt_text(&#39;EBB7C703E675DB3DA397038B4C17823C&#39;) FROM dual; -- → hello</pre><ul><li><strong>Create the crypto functions</strong> (one-time): run the CREATE OR REPLACE FUNCTION blocks from the <em>DBMS_CRYPTO setup</em> section above in the same schema that your app connects to (e.g. SYSTEM). These only need to be created once per database, not per app run.</li><li><strong>Create the crypto functions</strong> in your target schema (the SQL block under <em>DBMS_CRYPTO setup</em> above). The entity&#39;s @ColumnTransformer calls these by unqualified name, so they must be reachable from the connecting user&#39;s default search path.</li><li><strong>Run the app</strong>: ./gradlew bootRun. ddl-auto=create-drop will (re)create the users table with firstname/lastname as RAW(2000). ApplicationReadyEvent seeds three rows. Server binds on :8082.</li><li><strong>Hit the endpoint</strong>: GET http://localhost:8082/users?firstname=Anıl3&amp;lastname=Senocak3 (see src/main/resources/requests.http).</li></ul><p>Override datasource defaults with the ORACLE_URL / ORACLE_USERNAME / ORACLE_PASSWORD env vars.</p><h3>Caveats and tradeoffs</h3><ul><li><strong>Indexes on encrypted columns are useless</strong> unless you also store a deterministic blind index (e.g. HMAC of the lowercased plaintext) in a sibling column and query against that. The current setup forces a full-table decrypt for every LIKE fine for the demo, not fine at scale.</li><li><strong>CPU cost is per-row</strong>. Every selected row incurs a DBMS_CRYPTO.DECRYPT call. Watch query plans on hot tables; a function-based index on decrypt_text(col) would defeat the whole purpose of encrypting at rest.</li><li><strong>ddl-auto=create-drop</strong> in application.yml is convenient for a demo but obviously not what you want in production - switch to validate and manage schema with explicit migrations (Flyway / Liquibase). The encrypt_text / decrypt_text functions must be deployed via the same migration tooling, ahead of any column DDL that references them.</li><li><strong>The </strong><strong>RAW(2000) ceiling</strong> means plaintexts whose ciphertext would exceed ~2000 bytes need a BLOB column and the corresponding BLOBreturning function signatures.</li><li><strong>NULL handling</strong>: the wrappers above treat NULL plaintext the same as Oracle&#39;s NULL arithmetic encrypt_text(NULL) returns NULL (no row encrypted), and decrypt_text(NULL) returns NULL. The nullable = false on the JPA columns is the layer that actually enforces non-null.</li></ul><p><a href="https://github.com/senocak/Spring-Oracle-Column-Level-Encryption-Decryption">GitHub - senocak/Spring-Oracle-Column-Level-Encryption-Decryption: Spring Oracle Column Level Encryption Decryption</a></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84cf47a2c8fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/turkcell/column-level-encryption-decryption-with-oracle-dbms-crypto-in-spring-boot-84cf47a2c8fa">Column-Level Encryption / Decryption with Oracle `DBMS_CRYPTO` in Spring Boot</a> was originally published in <a href="https://medium.com/turkcell">turkcell</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Spring AI MCP Tools in Swagger UI]]></title>
            <link>https://medium.com/turkcell/testing-spring-ai-mcp-tools-in-swagger-ui-f52190506311?source=rss-53be7dd28340------2</link>
            <guid isPermaLink="false">https://medium.com/p/f52190506311</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Anil Senocak]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 08:53:32 GMT</pubDate>
            <atom:updated>2026-07-27T12:14:34.926Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iuWmtzM_MfeINI-Vr-s_aA.gif" /></figure><p>If you are building AI agents with Spring AI, you are likely exploring the <strong>Model Context Protocol (MCP)</strong>. MCP is a game-changer for AI applications, standardizing how AI models interact with external tools and data sources.</p><p>However, if you’ve set up an MCP server in Spring Boot, you might have noticed a slight downgrade in your Developer Experience when it comes to API documentation. Because MCP communicates via <strong><em>JSON-RPC 2.0</em></strong> over a single /mcp endpoint, standard OpenAPI (Swagger) generation doesn&#39;t know how to document your individual tools. Instead of a beautiful list of endpoints, you get a single POST /mcp route. Testing your tools means manually crafting JSON-RPC payloads in Postman or curl.</p><p>Let’s fix that.</p><h3>The Solution: A Custom OpenAPI Bridge</h3><p>We can bridge this gap by writing a custom OpenApiCustomizer bean. This solution dynamically scans your Spring application context for any methods annotated with @McpTool and injects ready-to-use JSON-RPC payload examples directly into your Swagger UI.</p><p>Here’s how I wired it up with a custom OpenApiCustomizer so every @McpTool method becomes a testable, documented example in Swagger.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19fa6bc2a8172083674e27e0376e9560/href">https://medium.com/media/19fa6bc2a8172083674e27e0376e9560/href</a></iframe><h3>How It Works</h3><p>Here is a quick breakdown of the magic happening under the hood:</p><h4>1. Standard Protocol Methods</h4><p>The code manually defines the baseline JSON-RPC payloads required by the MCP specification, specifically initialize and tools/list. This gives you one-click access to handshake with your server and verify your tools are registered.</p><h4>2. Reflection &amp; Context Scanning</h4><p>This is where the automation happens. By injecting the ListableBeanFactory, the customizer iterates through every bean in your Spring context. It uses Spring&#39;s ReflectionUtils and AopUtils (crucial if your beans are proxied by Spring) to inspect the methods of each class.</p><h4>3. Annotation Detection</h4><p>When it finds a method annotated with @McpTool, it inspects the method signature, extracts the parameter names and types, and constructs a perfectly formatted tools/call JSON-RPC payload.</p><h4>4. Swagger UI Injection</h4><p>Finally, it groups all these examples and binds them to a single POST /mcp endpoint in the OpenAPI schema. It also ensures the necessary headers (mcp-session-id and Accept) are documented.</p><h4>The Result</h4><p>When you boot up your application and navigate to /swagger-ui.html, your /mcp endpoint will now feature a rich <strong>Examples</strong> dropdown menu. You can simply select a tool, and Swagger UI will populate the request body with the exact JSON-RPC payload required to execute it.</p><p>🎉 No more guesswork, no more manual payload typing just seamless testing for your Spring AI agents.</p><p><a href="https://github.com/senocak?tab=repositories">senocak - Repositories</a></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f52190506311" width="1" height="1" alt=""><hr><p><a href="https://medium.com/turkcell/testing-spring-ai-mcp-tools-in-swagger-ui-f52190506311">Testing Spring AI MCP Tools in Swagger UI</a> was originally published in <a href="https://medium.com/turkcell">turkcell</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Oracle Dynamic ID Generator For Spring Boot]]></title>
            <link>https://medium.com/turkcell/oracle-dynamic-id-generator-for-spring-boot-efad48aa55ef?source=rss-53be7dd28340------2</link>
            <guid isPermaLink="false">https://medium.com/p/efad48aa55ef</guid>
            <category><![CDATA[oracle]]></category>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[oracle-database]]></category>
            <dc:creator><![CDATA[Anil Senocak]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 06:16:59 GMT</pubDate>
            <atom:updated>2026-06-24T06:16:59.331Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://github.com/senocak/Spring-Oracle-Dynamic-Id-Generation">GitHub - senocak/Spring-Oracle-Dynamic-Id-Generation: Spring Oracle Dynamic Id Generation</a></p><p>This project is a <strong>Spring Boot</strong> + <strong>Kotlin</strong> + <strong>Oracle</strong> sample application that demonstrates how to generate entity IDs dynamically using a custom Hibernate identifier generator backed by Oracle sequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v3A7425NXAz-kA35xL3rZw.jpeg" /><figcaption>Spring Kotlin Oracle Dynamic ID Generator</figcaption></figure><p>The main idea is to:</p><ul><li>use a reusable custom <strong>IdentifierGenerator</strong></li><li>determine Oracle sequence names dynamically from entity metadata</li><li>fetch IDs either <strong>one by one</strong> or <strong>in batches</strong></li><li>keep a small in-memory pool of prefetched IDs to reduce database round trips during bulk inserts</li><li>support JDBC batching efficiently</li></ul><p>The project compares two different approaches side-by-side:</p><ol><li>Dynamic custom sequence generation (User)</li><li>Standard JPA <strong>@SequenceGenerator</strong> (Role)</li></ol><p>This makes the project useful as a reference for teams that want flexible Oracle ID generation without hardcoding a sequence generator on every entity.</p><h4>Problem the Project Solves</h4><p>When using Oracle with JPA/Hibernate, sequence-based IDs are common. However, the default approach usually requires every entity to declare its own fixed configuration, for example:</p><pre>@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = &quot;SEQ_USER_GENERATOR&quot;)<br>@SequenceGenerator(name = &quot;SEQ_USER_GENERATOR&quot;, sequenceName = &quot;users_seq&quot;, allocationSize = 1)</pre><p>This works well but becomes repetitive when many entities follow a naming convention such as:</p><ul><li>table <strong>users</strong> -&gt; sequence <strong>users_seq</strong></li><li>table <strong>orders</strong> -&gt; sequence <strong>orders_seq</strong></li><li>table <strong>customers</strong> -&gt; sequence <strong>customers_seq</strong></li></ul><p>This project centralizes sequence handling in a reusable generator so that the application can:</p><ul><li>derive the sequence name automatically</li><li>support bulk insert scenarios more efficiently</li><li>keep entity definitions simpler</li><li>still work with Oracle sequence semantics</li></ul><h3>Core Solution</h3><h4>Custom Hibernate ID Generator</h4><p>The core component is <strong>DynamicSequenceGenerator</strong>. Its responsibilities are:</p><ul><li>inspect the entity being persisted</li><li>resolve the Oracle sequence name dynamically</li><li>fetch the next sequence value from Oracle</li><li>optionally fetch multiple IDs in a single SQL query</li><li>cache prefetched IDs in an in-memory queue</li></ul><p>The generator is attached to the <strong>User</strong> entity through:</p><pre>@GeneratedValue(generator = &quot;dynamic-seq&quot;)<br>@GenericGenerator(name = &quot;dynamic-seq&quot;, strategy = &quot;com.github.senocak.DynamicSequenceGenerator&quot;)</pre><h4>Dynamic Sequence Name Resolution</h4><p>The generator determines the sequence name using conventions:</p><ul><li>if the entity contains <strong>@Table(name = “…”)</strong> use <strong>&lt;table_name&gt;_seq</strong></li><li>otherwise, use <strong>&lt;entity_class_name_lowercase&gt;_seq</strong></li></ul><p>This means the sequence naming rule is defined once in the generator rather than repeated across all entities.</p><h4>Batch-Aware ID Fetching</h4><p>For bulk insert operations, the generator can fetch multiple IDs in one Oracle query:</p><pre>SELECT users_seq.NEXTVAL FROM dual CONNECT BY LEVEL &lt;= ?</pre><p>Returned IDs are stored in a temporary in-memory queue and reused during persistence. This reduces database round trips significantly compared with fetching IDs one-by-one.</p><h4>Thread-Local Batch Context</h4><p><strong>IdGenerationContext</strong> stores the desired batch size using <strong>ThreadLocal</strong>. Before calling <strong>saveAll</strong>, the app sets the batch size for the current work unit. The generator reads that value and decides whether to:</p><ul><li>fetch a single ID</li><li>or fetch a batch of IDs into the local pool</li></ul><p>After persistence, the thread-local state is cleared to avoid leaking configuration into later operations.</p><h3>Dynamic ID Generation Details</h3><h4>Single ID path</h4><p>If <strong>batchSize &lt;= 1</strong>, the generator executes:</p><pre>SELECT &lt;sequence&gt;.NEXTVAL FROM dual</pre><p>This is the simple path for one-at-a-time inserts.</p><h4>Batch path</h4><p>If <strong>batchSize &gt; 1</strong>, the generator executes:</p><pre>SELECT &lt;sequence&gt;.NEXTVAL FROM dual CONNECT BY LEVEL &lt;= ?</pre><p>The returned values are stored in an internal queue and reused by later <strong>generate()</strong> calls.</p><h4>Why this is useful</h4><p>Benefits:</p><ul><li>fewer Oracle calls during bulk insert operations</li><li>reusable convention-based ID strategy</li><li>less annotation repetition across entities</li><li>easy to adapt for multiple tables following the same sequence naming rule</li></ul><h4>Summary</h4><p>This application demonstrates a <strong>Dynamic Oracle ID generation strategy </strong>for Spring Boot and Kotlin.</p><p>Its main contribution is a custom Hibernate generator that:</p><ul><li>derives sequence names dynamically</li><li>supports bulk ID prefetching</li><li>uses Oracle efficiently during batched persistence</li><li>keeps entity configuration simpler when a naming convention is available In short, it is a compact reference implementation of dynamic sequence-based ID generation with Spring Boot, Kotlin, Hibernate, and Oracle.</li></ul><p>For custom implementation;</p><pre>2026-05-27T23:21:33.780+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:4, Time:75, Success:True<br>Type:Prepared, Batch:False, QuerySize:1, BatchSize:0<br>Query:[&quot;SELECT users_seq.NEXTVAL FROM dual CONNECT BY LEVEL &lt;= ?&quot;]<br>Params:[(5)]<br>2026-05-27T23:21:33.783+03:00  INFO 49079 --- [SpringKotlinOracle] [           main] c.g.senocak.DynamicSequenceGenerator     : Fetched 5 ids into local pool (requested 5). Returning id after batch fetch: 1<br>2026-05-27T23:21:33.800+03:00  INFO 49079 --- [SpringKotlinOracle] [           main] c.g.senocak.DynamicSequenceGenerator     : Returning id from local pool: 2<br>2026-05-27T23:21:33.801+03:00  INFO 49079 --- [SpringKotlinOracle] [           main] c.g.senocak.DynamicSequenceGenerator     : Returning id from local pool: 3<br>2026-05-27T23:21:33.801+03:00  INFO 49079 --- [SpringKotlinOracle] [           main] c.g.senocak.DynamicSequenceGenerator     : Returning id from local pool: 4<br>2026-05-27T23:21:33.802+03:00  INFO 49079 --- [SpringKotlinOracle] [           main] c.g.senocak.DynamicSequenceGenerator     : Returning id from local pool: 5<br>2026-05-27T23:21:33.836+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:4, Time:14, Success:True<br>Type:Prepared, Batch:True, QuerySize:1, BatchSize:5<br>Query:[&quot;insert into users (name,id) values (?,?)&quot;]<br>Params:[(John 1 0,1),(John 2 1,2),(John 3 2,3),(John 4 3,4),(John 5 4,5)]<br>2026-05-27T23:21:33.849+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:5, Time:0, Success:True<br>Type:Prepared, Batch:False, QuerySize:1, BatchSize:0<br>Query:[&quot;SELECT users_seq.NEXTVAL FROM dual CONNECT BY LEVEL &lt;= ?&quot;]<br>Params:[(5)]<br>2026-05-27T23:21:33.849+03:00  INFO 49079 --- [SpringKotlinOracle] [           main] c.g.senocak.DynamicSequenceGenerator     : Fetched 5 ids into local pool (requested 5). Returning id after batch fetch: 6<br>2026-05-27T23:21:33.850+03:00  INFO 49079 --- [SpringKotlinOracle] [           main] c.g.senocak.DynamicSequenceGenerator     : Returning id from local pool: 7<br>2026-05-27T23:21:33.850+03:00  INFO 49079 --- [SpringKotlinOracle] [           main] c.g.senocak.DynamicSequenceGenerator     : Returning id from local pool: 8<br>2026-05-27T23:21:33.850+03:00  INFO 49079 --- [SpringKotlinOracle] [           main] c.g.senocak.DynamicSequenceGenerator     : Returning id from local pool: 9<br>2026-05-27T23:21:33.850+03:00  INFO 49079 --- [SpringKotlinOracle] [           main] c.g.senocak.DynamicSequenceGenerator     : Returning id from local pool: 10<br>2026-05-27T23:21:33.858+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:5, Time:7, Success:True<br>Type:Prepared, Batch:True, QuerySize:1, BatchSize:5<br>Query:[&quot;insert into users (name,id) values (?,?)&quot;]<br>Params:[(John 6 0,6),(John 7 1,7),(John 8 2,8),(John 9 3,9),(John 10 4,10)]<br>2026-05-27T23:21:33.875+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:6, Time:0, Success:True<br>Type:Prepared, Batch:False, QuerySize:1, BatchSize:0<br>Query:[&quot;SELECT users_seq.NEXTVAL FROM dual CONNECT BY LEVEL &lt;= ?&quot;]<br>Params:[(2)]<br>2026-05-27T23:21:33.875+03:00  INFO 49079 --- [SpringKotlinOracle] [           main] c.g.senocak.DynamicSequenceGenerator     : Fetched 2 ids into local pool (requested 2). Returning id after batch fetch: 11<br>2026-05-27T23:21:33.876+03:00  INFO 49079 --- [SpringKotlinOracle] [           main] c.g.senocak.DynamicSequenceGenerator     : Returning id from local pool: 12<br>2026-05-27T23:21:33.882+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:6, Time:4, Success:True<br>Type:Prepared, Batch:True, QuerySize:1, BatchSize:2<br>Query:[&quot;insert into users (name,id) values (?,?)&quot;]<br>Params:[(John 11 0,11),(John 12 1,12)]</pre><p>For traditional implementation;</p><pre>2026-05-27T23:21:38.967+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:7, Time:20, Success:True<br>Type:Prepared, Batch:False, QuerySize:1, BatchSize:0<br>Query:[&quot;select users_seq.nextval&quot;]<br>Params:[()]<br>2026-05-27T23:21:38.971+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:7, Time:0, Success:True<br>Type:Prepared, Batch:False, QuerySize:1, BatchSize:0<br>Query:[&quot;select users_seq.nextval&quot;]<br>Params:[()]<br>2026-05-27T23:21:38.973+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:7, Time:0, Success:True<br>Type:Prepared, Batch:False, QuerySize:1, BatchSize:0<br>Query:[&quot;select users_seq.nextval&quot;]<br>Params:[()]<br>2026-05-27T23:21:38.974+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:7, Time:0, Success:True<br>Type:Prepared, Batch:False, QuerySize:1, BatchSize:0<br>Query:[&quot;select users_seq.nextval&quot;]<br>Params:[()]<br>2026-05-27T23:21:38.976+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:7, Time:0, Success:True<br>Type:Prepared, Batch:False, QuerySize:1, BatchSize:0<br>Query:[&quot;select users_seq.nextval&quot;]<br>Params:[()]<br>2026-05-27T23:21:38.977+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:7, Time:0, Success:True<br>Type:Prepared, Batch:False, QuerySize:1, BatchSize:0<br>Query:[&quot;select users_seq.nextval&quot;]<br>Params:[()]<br>2026-05-27T23:21:38.978+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:7, Time:0, Success:True<br>Type:Prepared, Batch:False, QuerySize:1, BatchSize:0<br>Query:[&quot;select users_seq.nextval&quot;]<br>Params:[()]<br>2026-05-27T23:21:38.979+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:7, Time:0, Success:True<br>Type:Prepared, Batch:False, QuerySize:1, BatchSize:0<br>Query:[&quot;select users_seq.nextval&quot;]<br>Params:[()]<br>2026-05-27T23:21:38.991+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:7, Time:11, Success:True<br>Type:Prepared, Batch:False, QuerySize:1, BatchSize:0<br>Query:[&quot;select users_seq.nextval&quot;]<br>Params:[()]<br>2026-05-27T23:21:38.992+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:7, Time:0, Success:True<br>Type:Prepared, Batch:False, QuerySize:1, BatchSize:0<br>Query:[&quot;select users_seq.nextval&quot;]<br>Params:[()]<br>2026-05-27T23:21:38.993+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:7, Time:0, Success:True<br>Type:Prepared, Batch:False, QuerySize:1, BatchSize:0<br>Query:[&quot;select users_seq.nextval&quot;]<br>Params:[()]<br>2026-05-27T23:21:38.994+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:7, Time:0, Success:True<br>Type:Prepared, Batch:False, QuerySize:1, BatchSize:0<br>Query:[&quot;select users_seq.nextval&quot;]<br>Params:[()]<br>2026-05-27T23:21:39.009+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:7, Time:12, Success:True<br>Type:Prepared, Batch:True, QuerySize:1, BatchSize:10<br>Query:[&quot;insert into roles (name,id) values (?,?)&quot;]<br>Params:[(John 0,13),(John 1,14),(John 2,15),(John 3,16),(John 4,17),(John 5,18),(John 6,19),(John 7,20),(John 8,21),(John 9,22)]<br>2026-05-27T23:21:39.010+03:00 DEBUG 49079 --- [SpringKotlinOracle] [           main] n.t.d.l.l.SLF4JQueryLoggingListener      : <br>Name:dataSource, Connection:7, Time:0, Success:True<br>Type:Prepared, Batch:True, QuerySize:1, BatchSize:2<br>Query:[&quot;insert into roles (name,id) values (?,?)&quot;]<br>Params:[(John 10,23),(John 11,24)]</pre><h3>Scenario 1 (users table)</h3><ul><li><strong>Total Records Inserted:</strong> 12</li><li><strong>ID Generation Strategy:</strong> Bulk Fetch (CONNECT BY LEVEL)</li><li><strong>ID Fetch Queries Executed:</strong> 3 (Fetching 5, 5, and 2)</li><li><strong>Insert Queries Executed:</strong> 3 (Batches of 5, 5, and 2)</li><li><strong>Total Database Round-trips:</strong> 6</li></ul><h3>Scenario 2 (roles table)</h3><ul><li><strong>Total Records Inserted:</strong> 12</li><li><strong>ID Generation Strategy:</strong> Single Fetch (NEXTVAL)</li><li><strong>ID Fetch Queries Executed:</strong> 12 (Fetching 1 at a time)</li><li><strong>Insert Queries Executed:</strong> 2 (Batches of 10 and 2)</li><li><strong>Total Database Round-trips:</strong> 14</li></ul><p><a href="https://github.com/senocak/Spring-Oracle-Dynamic-Id-Generation">GitHub - senocak/Spring-Oracle-Dynamic-Id-Generation: Spring Oracle Dynamic Id Generation</a></p><p>Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efad48aa55ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/turkcell/oracle-dynamic-id-generator-for-spring-boot-efad48aa55ef">Oracle Dynamic ID Generator For Spring Boot</a> was originally published in <a href="https://medium.com/turkcell">turkcell</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Data File Repository: Local JSON Storage in Spring Boot]]></title>
            <link>https://medium.com/turkcell/spring-data-file-repository-local-json-storage-in-spring-boot-462e15b72a1d?source=rss-53be7dd28340------2</link>
            <guid isPermaLink="false">https://medium.com/p/462e15b72a1d</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-data]]></category>
            <dc:creator><![CDATA[Anil Senocak]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 13:45:06 GMT</pubDate>
            <atom:updated>2026-06-18T07:28:14.109Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Spring Data File Repository: Local JSON Storage in Spring Boot" src="https://cdn-images-1.medium.com/max/1024/1*3J7qcw-KTJLNpDC0XldNJA.png" /></figure><p><a href="https://github.com/senocak/Spring-Data-File-Repository">GitHub - senocak/Spring-Data-File-Repository</a></p><p>In modern backend architectures, we usually rely on traditional database servers like PostgreSQL, MySQL, or Oracle. However, setting up a database infrastructure for a small microservice, a rapid proof-of-concept (PoC), or a local utility service can introduce unnecessary infrastructure overhead.</p><p>This project demonstrates how to implement a lightweight, thread-safe, and local JSON file-based data store directly inside a Spring Boot application, maintaining the standard repository pattern design.</p><h4>🎯 The Problem: Infrastructure Overhead for Lightweight Services</h4><p>When developing standalone microservices, tools, or fast prototypes, spinning up a heavy relational database or managing external Docker containers just to persist a few records introduces unwanted friction.</p><p>We need a persistent data store that is:</p><ul><li>🪶 <strong>Zero-dependency:</strong> No external database engines required.</li><li>📦 <strong>Self-contained:</strong> Data stored directly inside the project directory footprint.</li><li>⚡ <strong>Fast &amp; Lightweight:</strong> In-memory operational speeds with instant auto-commit to disk.</li></ul><h3>⚙️ Core Logic</h3><p>The <strong>Spring Data File Repository</strong> abstracts file persistence in a way similar to Spring Data JPA, but instead of database tables, it works with file storage backends (local disk, S3-compatible storage, or custom implementations).</p><h4>Repository Abstraction (Spring-Data Style)</h4><p>You define repositories like:</p><pre>@Repository<br>public interface ParkRepository extends JsonRepository&lt;Park, Long&gt; {<br>    List&lt;Park&gt; findAll();<br>    Page&lt;Park&gt; findAllByOrderByParkIDAsc(Pageable pageable);<br>    Page&lt;Park&gt; findAllByParkNameContaining(String parkName, Pageable pageable);<br>}</pre><p>Core operations:</p><ul><li>save(file)</li><li>saveAll(files)</li><li>findById(id)</li><li>existsById(id)</li><li>findAll()</li><li>findAllById(id)</li><li>count()</li><li>deleteById(id)</li><li>delete(file)</li><li>deleteAllById(id)</li><li>deleteAll(files)</li></ul><p>Also the great feature that comes from Spring Data which is derived methods that examples shown above.</p><p>Internally, these behave like Spring Data repositories but delegate to storage adapters.</p><h4>🛠️ The Solution: A Generic, Thread-Safe File Repository</h4><p>This library provides a fully functional, generic repository pattern backed by local JSON file storage. It leverages Jackson for high-performance serialization, thread-safe memory caches for lookups, and explicit file-level locking mechanisms to prevent corruption.</p><h4>✨ Key Features</h4><ul><li>📂 <strong>JSON File Persistence:</strong> Stores entities cleanly as JSON arrays on disk.</li><li>🔄 <strong>Full CRUD Implementation:</strong> Standard Create, Read, Update, and Delete operations.</li><li>🔒 <strong>Thread-Safe Architecture:</strong> Uses explicit concurrent read-write locks for file access.</li><li>💾 <strong>Auto-Save Mechanism:</strong> Automatically synchronizes in-memory changes to files.</li><li>🌐 <strong>REST API &amp; Best Practices:</strong> Complete demonstration featuring clean Dependency Injection, Global Exception Handling, and SLF4J logging.</li><li>🧪 <strong>Comprehensive Tests:</strong> Includes complete integration test coverage.</li></ul><h4>📐 Deep Dive: How It Works Under the Hood</h4><pre>[ Client / Controller ]<br>│<br>▼<br>[ Service Layer ] (Validation / Business Rules)<br>│<br>▼<br>[ Repository Layer ] ──▶ [ In-Memory Cache (CopyOnWriteArrayList) ]<br>│<br>▼<br>[ JsonFileStore ]  ──▶ [ ReadWriteLock Protection ] ──▶ [ Local .json File ]</pre><h4>⚙️ JsonFileStore (Core Utility)</h4><ul><li><strong>Concurrent Safety:</strong> Uses a ReadWriteLock to ensure multiple threads can read simultaneously, while exclusive access is guaranteed during a write phase.</li><li><strong>Jackson Mapping:</strong> Utilizes Jackson’s ObjectMapper for robust type-safe serialization/deserialization.</li><li><strong>Resilient I/O:</strong> Automatically initializes and constructs the underlying storage directories and target files safely if they do not exist.</li></ul><h4>🗄️ Repository Layer</h4><ul><li><strong>Fast Reads:</strong> Maintains an internal thread-safe CopyOnWriteArrayList acting as a lightning-fast in-memory cache layer.</li><li><strong>Lazy Initialization:</strong> Reads data from disk into memory exactly once during application startup via @PostConstruct.</li><li><strong>Sync-on-Write:</strong> Commits data mutations back to the file array instantly after each transactional repository method.</li></ul><h4>Configuration</h4><p>Externalizing parameters is essential. Define your application storage path easily inside your src/main/resources/application.yml:</p><pre>spring:<br>  data:<br>    json:<br>      file-path: ${user.dir}/example/data</pre><h4>🚀 Adding New Entities &amp; Data Structures</h4><p>The system natively supports multiple entity structures. The repository directory contains pre-configured implementations for both User and Product models. To add your own custom entity; Define your model class in the model/package. Build a repository extending the generic file store pattern. Expose your business requirements through your service and controller layer.</p><p>JSON files are stored in the data/ directory:</p><ul><li>data/users.json - User data</li><li>data/products.json - Product data (if used)</li></ul><h4>Adding New Entities</h4><p>To add a new entity (e.g., Note, Product):</p><ol><li>Create the model class in model/ package</li><li>Create a repository class in repository/ package (similar to UserRepository)</li><li>Create a service class in service/ package (optional)</li><li>Create a controller class in controller/ package (optional)</li></ol><p>Example: The Product entity is already included as a reference implementation.</p><h4>Best Practices Implemented</h4><ul><li>✅ Dependency Injection via constructor</li><li>✅ Configuration properties externalized</li><li>✅ Global exception handling</li><li>✅ Proper logging with SLF4J</li><li>✅ RESTful API design</li><li>✅ Separation of concerns (Controller → Service → Repository)</li><li>✅ Thread-safe operations</li><li>✅ Comprehensive error handling</li><li>✅ Integration tests</li></ul><h4>⚠️ Architectural Limitations</h4><ul><li><strong>Not for Production</strong>: While this approach provides a friction-free experience for localized setups, keep these trade-offs in mind before planning your production architecture.</li><li><strong>Scalability</strong>: Queries utilize linear search through the in-memory array list (O(N)). Large datasets will increase look-up times.</li><li><strong>Concurrent Writes</strong>: No Multi-Instance Horizontal Scaling; If multiple separate application instances attempt to read/write to the exact same file pathway simultaneously without a shared file system lock, conflicts will occur.</li><li><strong>Query Performance</strong>: Linear search through in-memory list</li><li><strong>No Transactions</strong>: There are no transaction rollback capabilities stretching across multiple distinct entity alterations.</li></ul><p><a href="https://github.com/senocak/Spring-Data-File-Repository">GitHub - senocak/Spring-Data-File-Repository</a></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=462e15b72a1d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/turkcell/spring-data-file-repository-local-json-storage-in-spring-boot-462e15b72a1d">Spring Data File Repository: Local JSON Storage in Spring Boot</a> was originally published in <a href="https://medium.com/turkcell">turkcell</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge Your Spring Boot Apps: Dynamic Configuration with JedisPubSub]]></title>
            <link>https://medium.com/turkcell/supercharge-your-spring-boot-apps-dynamic-configuration-with-jedispubsub-475c2cf96b10?source=rss-53be7dd28340------2</link>
            <guid isPermaLink="false">https://medium.com/p/475c2cf96b10</guid>
            <category><![CDATA[jedi]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Anil Senocak]]></dc:creator>
            <pubDate>Sun, 24 May 2026 12:28:36 GMT</pubDate>
            <atom:updated>2026-06-09T06:36:12.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oskX8kf94sgHMpbzwSdeAA.png" /><figcaption>Supercharge Your Spring Boot Apps: Dynamic Configuration with JedisPubSub</figcaption></figure><p>In today’s fast-paced development world, the ability to update application configuration on the fly-without redeploying or restarting your service is a game changer. While Spring Cloud Config is a popular solution, sometimes you want a lightweight, cloud-agnostic approach. That’s where <strong>JedisPubSub</strong> comes in.</p><p><a href="https://github.com/senocak/Spring-Kotlin-Redis-DynamicConfig-JedisPubSub">GitHub - senocak/Spring-Kotlin-Redis-DynamicConfig-JedisPubSub: Spring-Kotlin-Redis-DynamicConfig-JedisPubSub</a></p><p>is a Java client library for Redis. JedisPubSub is an abstract class in Jedis that provides a convenient way to implement Redis <strong>Publish/Subscribe (Pub/Sub)</strong> messaging in Java applications.</p><h3>What Redis Pub/Sub Does</h3><p>Redis Pub/Sub allows applications to communicate using channels:</p><ul><li><strong>Publisher</strong> sends messages to a channel.</li><li><strong>Subscriber</strong> listens to that channel and receives messages in real time.</li></ul><p>This is useful for:</p><ul><li>Event-driven systems</li><li>Notifications</li><li>Cache invalidation</li><li>Chat applications</li><li>Distributed communication</li></ul><h3>What JedisPubSub Provides</h3><p>JedisPubSub defines callback methods that are invoked automatically when Pub/Sub events occur.</p><p>JedisPubSub works by combining three pieces:</p><ol><li>A connection to Redis</li><li>A listener object that extends JedisPubSub</li><li>A blocking subscription loop that waits for messages</li></ol><h3>🚦 Getting Started</h3><h3>Run Redis Cluster locally (or use Docker):</h3><pre>version: &#39;3.7&#39;<br>services:<br>  redis-cluster:<br>    build:<br>      context: https://github.com/senocak/redis-single-node-cluster.git#main:build<br>      args:<br>        - REDIS_BASE_IMAGE=redis:7.2-alpine<br>    environment:<br>      - REDIS_CONFIG_CLUSTER_ANNOUNCE_IP=127.0.0.1<br>    ports:<br>      - &quot;6379:6379&quot;<br>    networks:<br>      - ops<br>networks:<br>  ops:</pre><pre>docker-compose up -d</pre><p>Make sure you enabled Redis keyspace notifications by running the following command in your Redis CLI:</p><pre>redis-cli config set notify-keyspace-events KEA</pre><h3>Configure Redis in application.yml</h3><pre>spring:<br>  data:<br>    redis:<br>      cluster:<br>        nodes: localhost:6379  # Update with your Redis server address<br>      database: 0<br>      timeout: 60000</pre><h3>Configuration default values:</h3><p>The application can be configured through the application.yml file:</p><pre># Using redis-cli<br>redis-cli SET &quot;redis-pub-sub-config:ping&quot; &quot;Hello, Dynamic World!&quot;</pre><h3>Start the app and test:</h3><p>The application includes a simple endpoint to test dynamic configuration:</p><pre># Using curl<br>curl http://localhost:8082/ping<br>&gt; Hello, Dynamic World!</pre><p>The response will show the current value of the ping configuration.</p><h3>How It Works</h3><ol><li>The application scans all Spring beans for fields annotated with @RedisConfig</li><li>It registers these fields in a registry with their default values</li><li>It subscribes to Redis keyspace notifications for the configured keys</li><li>When a key changes in Redis, the application receives a notification</li><li>The field value is updated with the new value from Redis</li></ol><p><a href="https://github.com/senocak/Spring-Kotlin-Redis-DynamicConfig-JedisPubSub">GitHub - senocak/Spring-Kotlin-Redis-DynamicConfig-JedisPubSub: Spring-Kotlin-Redis-DynamicConfig-JedisPubSub</a></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=475c2cf96b10" width="1" height="1" alt=""><hr><p><a href="https://medium.com/turkcell/supercharge-your-spring-boot-apps-dynamic-configuration-with-jedispubsub-475c2cf96b10">Supercharge Your Spring Boot Apps: Dynamic Configuration with JedisPubSub</a> was originally published in <a href="https://medium.com/turkcell">turkcell</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Building Dynamic Queries in Spring Boot with a Specification Builder]]></title>
            <link>https://medium.com/turkcell/building-dynamic-queries-in-spring-boot-with-a-specification-builder-83416a4b2068?source=rss-53be7dd28340------2</link>
            <guid isPermaLink="false">https://medium.com/p/83416a4b2068</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[specifications]]></category>
            <category><![CDATA[jpa]]></category>
            <dc:creator><![CDATA[Anil Senocak]]></dc:creator>
            <pubDate>Tue, 12 May 2026 04:55:44 GMT</pubDate>
            <atom:updated>2026-06-09T06:35:31.119Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://github.com/senocak/SpringBoot-Specification-Builder">GitHub - senocak/SpringBoot-Specification-Builder: SpringBoot Specification Builder</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CkFtAweKcnOsYTZ1s_AaZw.png" /></figure><p>Modern backend applications rarely deal with simple queries. Once users demand filtering, searching, sorting, and combining multiple conditions dynamically, traditional repository methods quickly become unmanageable.</p><p>If you’ve ever written queries like then you already know the pain.</p><pre>WHERE (:name IS NULL OR name LIKE %:name%)<br>AND (:status IS NULL OR status = :status)<br>AND (:date IS NULL OR created_at &gt; :date)</pre><p>This is exactly where a <strong>Specification Builder</strong> approach shines.</p><p>In this article, we’ll explore how a <strong>Spring Boot Specification Builder</strong> project simplifies dynamic querying, eliminates boilerplate, and provides a clean, scalable architecture.</p><h3>🧩 The Problem with Traditional Querying</h3><p>Spring Data JPA offers multiple ways to query:</p><ul><li>Derived query methods (findByNameAndStatus)</li><li>JPQL / Native queries</li><li>Criteria API</li><li>Specifications</li></ul><p>Among these, <strong>Specifications</strong> stand out for dynamic querying because they allow you to build predicates programmatically.</p><p>However, raw Specifications come with their own problems:</p><ul><li>Too much boilerplate</li><li>Hard to scale for complex filters</li><li>Repetitive predicate construction</li><li>Difficult to reuse</li></ul><h3>💡 The Idea Behind Specification Builder</h3><p>The Specification Builder project introduces a <strong>generic, reusable, and extensible way</strong> to construct dynamic queries. Instead of writing custom specifications for every entity, it allows:</p><p>✅ Generic filtering<br>✅ Operator-based querying (EQUAL, LIKE, GREATER_THAN, etc.)<br>✅ Dynamic field selection<br>✅ Clean API request structure<br>✅ Reusable and composable logic</p><p>In short: <strong>you define filters → builder generates the query</strong></p><h3>✨ Why You’ll Love It</h3><h3>1. 🔍 Deep Path Resolution (No More Join Nightmares)</h3><p>One of the most tedious parts of JPA Specifications is managing joins for nested entities. The library handles this automatically using dot notation.</p><pre>// This automatically creates all necessary LEFT JOINs for address and city<br>Specification&lt;User&gt; spec = SpecBuilder.forClass(User.class)<br>    .eq(&quot;address.city.name&quot;, &quot;New York&quot;)<br>    .build();</pre><h3>2. 🛡️ Built-in Null-Safety</h3><p>Dynamic search forms often send null values for optional filters. Instead of wrapping every condition in an if (value != null) block, <strong>Easy Specification</strong> does it for you. If a value is null, the condition is simply skipped.</p><pre>String email = null; // This will be automatically ignored<br>Specification&lt;User&gt; spec = SpecBuilder.forClass(User.class)<br>    .eq(&quot;email&quot;, email) <br>    .contains(&quot;name&quot;, &quot;John&quot;)<br>    .build();</pre><h3>3. 🛠️ Perfect for REST APIs</h3><p>Building a dynamic search endpoint? You can easily map your incoming filters to the SpecBuilder.</p><pre>@PostMapping(&quot;/search&quot;)<br>public List&lt;User&gt; search(@RequestBody SearchRequest request) {<br>    SpecBuilder&lt;User&gt; specBuilder = SpecBuilder.forClass(User.class);<br>    <br>    for (FilterDto filter : request.filters()) {<br>        // Map your dynamic filters here...<br>        specBuilder.eq(filter.field(), filter.value());<br>    }<br>    <br>    return userRepository.findAll(specBuilder.build());<br>}</pre><h3>📦 Getting Started</h3><h3>Installation</h3><p>Add the dependency to your pom.xml:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.github.senocak.easyspec&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-easy-specification&lt;/artifactId&gt;<br>    &lt;version&gt;1.0.1&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Or for Gradle:</p><pre>implementation &#39;com.github.senocak.easyspec:spring-boot-easy-specification:1.0.1&#39;</pre><h3>Quick Usage</h3><pre>import com.github.senocak.easyspec.builder.SpecBuilder;</pre><pre>import com.github.senocak.easyspec.builder.SpecBuilder;<br><br>Specification&lt;User&gt; spec = SpecBuilder.forClass(User.class)<br>    .eq(&quot;status&quot;, UserStatus.ACTIVE)<br>    .orderBy(&quot;createdAt&quot;, Sort.Direction.DESC)<br>    .build();<br><br>List&lt;User&gt; users = userRepository.findAll(spec);</pre><h3>🛠️ Feature Overview</h3><p>The SpecBuilder supports all the operations you&#39;d expect:</p><ul><li><strong>Comparison</strong>: eq, ne, greaterThan, lessThan, gte, lte, between, in.</li><li><strong>Null Checks</strong>: isNull, isNotNull.</li><li><strong>String Matching</strong>: contains, startsWith, endsWith.</li><li><strong>Sorting</strong>: orderBy.</li></ul><p><a href="https://github.com/senocak/SpringBoot-Specification-Builder">GitHub - senocak/SpringBoot-Specification-Builder: SpringBoot Specification Builder</a></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83416a4b2068" width="1" height="1" alt=""><hr><p><a href="https://medium.com/turkcell/building-dynamic-queries-in-spring-boot-with-a-specification-builder-83416a4b2068">🚀 Building Dynamic Queries in Spring Boot with a Specification Builder</a> was originally published in <a href="https://medium.com/turkcell">turkcell</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>