<?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 Tahitoa Merlin on Medium]]></title>
        <description><![CDATA[Stories by Tahitoa Merlin on Medium]]></description>
        <link>https://medium.com/@tahitoa.merlin?source=rss-e186e579e9d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9gVDXDqS7GQDi00mPs4a8A.jpeg</url>
            <title>Stories by Tahitoa Merlin on Medium</title>
            <link>https://medium.com/@tahitoa.merlin?source=rss-e186e579e9d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:30:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tahitoa.merlin/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[Setup a local Kubernetes cluster (Part 2/3)]]></title>
            <link>https://medium.com/@tahitoa.merlin/setup-a-local-kubernetes-cluster-2-2-bb7859301150?source=rss-e186e579e9d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb7859301150</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[kubernetes-cluster]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Tahitoa Merlin]]></dc:creator>
            <pubDate>Fri, 29 May 2026 11:29:24 GMT</pubDate>
            <atom:updated>2026-05-29T15:26:57.433Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous article [<a href="https://medium.com/@tahitoa.merlin/setup-a-local-kubernetes-cluster-9cdae6ef62a7">here</a>], we built a functional local cluster using strict minimum requirements.</p><p>However, it lacks key features: GatewayAPI (as Ingress is deprecated [<a href="https://kubernetes.io/blog/2025/11/11/ingress-nginx-retirement/">announcement</a>]), metrics monitoring, and services exposure (of LoadBalancer type).</p><p>Think of Kubernetes as a modular building system, similar to Lego bricks. This allows you to construct a cluster that fulfills your specific requirements.</p><p>To move beyond the default Flannel setup, we’ll uninstall the current CNI and install Cilium for enhanced observability and network policies</p><p>Start to drop the Flannel configuration:</p><pre>kubectl delete -f https://github.com/coreos/flannel/raw/master/Documentation/kube-flannel.yml</pre><p>And then follow the official documentation [<a href="https://docs.cilium.io/en/stable/gettingstarted/k8s-install-default/">here</a>] to install Cilium.</p><p>To prevent conflicts, verify that the Flannelconfiguration file is removed from (or save it in another folder)/etc/cni/net.d:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*NNUjM5HDtdFK07RvJvlZJA.png" /><figcaption>CNI plugins configuration files</figcaption></figure><p>CoreDNS pods may encounter errors when attempting to restart due to certain conflicts. To ensure all changes are applied correctly, you should reboot your system.</p><h4>Installation of GatewayAPI</h4><p>The Gateway API is a Kubernetes SIG specification that service providers implement in compliance with its requirements.</p><p>You can find all implementations [<a href="https://gateway-api.sigs.k8s.io/docs/implementations/list/">here</a>].</p><p>For this example, we will use the Gateway implementation; then proceed to the installation documentation [<a href="https://kgateway.dev/docs/envoy/latest/install/helm/">here</a>].</p><p>Now that the GatewayAPI is installed, install the sample app and create a simple gateway using the following snippet:</p><pre>kubectl apply -f https://raw.githubusercontent.com/kgateway-dev/kgateway/refs/heads/v2.3.x/examples/httpbin.yaml<br><br>kubectl apply -f- &lt;&lt;EOF<br>kind: Gateway<br>apiVersion: gateway.networking.k8s.io/v1<br>metadata:<br>  name: http<br>  namespace: kgateway-system<br>spec:<br>  gatewayClassName: kgateway<br>  listeners:<br>  - protocol: HTTP<br>    port: 8080<br>    name: http<br>    allowedRoutes:<br>      namespaces:<br>        from: All<br>EOF</pre><p>Then verify the deployment with the following commands:</p><p>List services:</p><pre>kubectl get svc -n kgateway-system<br>#NAME       TYPE           CLUSTER-IP       EXTERNAL-IP   PORT(S)                      AGE<br>#http       LoadBalancer   10.98.94.35      &lt;pending&gt;     8080:30469/TCP               2m28s<br>#kgateway   ClusterIP      10.111.145.154   &lt;none&gt;        9977/TCP,9093/TCP,9092/TCP   3m18s</pre><p>List Gateways:</p><pre>kubectl get gateway -n kgateway-system<br>#NAME   CLASS      ADDRESS   PROGRAMMED   AGE<br>#http   kgateway             True         3m13s</pre><p>Observe the “pending” state for the External IP field. While cloud provider typically handle this automatically, you can also also use <a href="https://metallb.io/">MetalLB</a> to assign an IP address on local environments (or when you build the cluster from scratch).</p><p>Now we install the LoadBalancer following the official documentation [<a href="https://metallb.io/installation/">here</a>].</p><p>Verify the deployment with the following commands:</p><p>List services:</p><pre>kubectl get pods -n metallb-system<br>#NAME                                     READY   STATUS    RESTARTS   AGE<br>#controller-595647bc76-c4wm6              1/1     Running   0          103s<br>#frr-k8s-daemon-hqmt7                     5/5     Running   0          103s<br>#frr-k8s-statuscleaner-58d8956cbd-7qqcn   1/1     Running   0          103s<br>#speaker-hbhlg                            1/1     Running   0          103s</pre><p>List pods:</p><pre>kubectl get pods -n metallb-system<br>#NAME                                     READY   STATUS    RESTARTS   AGE<br>#controller-595647bc76-c4wm6              1/1     Running   0          2m29s<br>#frr-k8s-daemon-hqmt7                     5/5     Running   0          2m29s<br>#frr-k8s-statuscleaner-58d8956cbd-7qqcn   1/1     Running   0          2m29s<br>#speaker-hbhlg                            1/1     Running   0          2m29s</pre><p>However, if the LoadBalancer service remains in a pending state:</p><pre>kubectl get svc -n kgateway-system<br>#NAME       TYPE           CLUSTER-IP       EXTERNAL-IP   PORT(S)                      AGE<br>#http       LoadBalancer   10.98.94.35      &lt;pending&gt;     8080:30469/TCP               2m28s<br>#kgateway   ClusterIP      10.111.145.154   &lt;none&gt;        9977/TCP,9093/TCP,9092/TCP   3m18s</pre><p>We must define an IP address pool for the LoadBalancer Service with the following configuration:</p><pre>kubectl apply -f- &lt;&lt;EOF<br>apiVersion: metallb.io/v1beta1<br>kind: IPAddressPool<br>metadata:<br>  name: default-pool<br>  namespace: metallb-system<br>spec:<br>  addresses:<br>    # Use addresses on the same subnet as your nodes<br>    # Ensure these IPs are not used by other devices on the network<br>    - 192.168.1.35-192.168.1.254<br>EOF</pre><p>In this configuration, we explicitly define an IP pool ranging from 192.168.1.35 to 192.168.1.254.</p><p>Verify the LoadBalancer service status:</p><pre>kubectl get svc -n kgateway-system<br>#NAME       TYPE           CLUSTER-IP       EXTERNAL-IP    PORT(S)                      AGE<br>#http       LoadBalancer   10.98.94.35      192.168.1.35   8080:30469/TCP               21m<br>#kgateway   ClusterIP      10.111.145.154   &lt;none&gt;         9977/TCP,9093/TCP,9092/TCP   22m</pre><p>We can now observe that LoadBalancer has an IP automatically assigned.</p><p>With the LoadBalancer and Gateway API successfully configured and running smoothly, we can now proceed to scale the cluster by adding additional worker nodes.</p><p>Let’s wrap up this series with the final step: adding worker nodes to the local machine.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb7859301150" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup a local Kubernetes cluster (Part 1/3)]]></title>
            <link>https://medium.com/@tahitoa.merlin/setup-a-local-kubernetes-cluster-9cdae6ef62a7?source=rss-e186e579e9d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cdae6ef62a7</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kubernetes-cluster]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Tahitoa Merlin]]></dc:creator>
            <pubDate>Wed, 27 May 2026 15:40:16 GMT</pubDate>
            <atom:updated>2026-05-29T15:26:37.252Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zKFlKoWWGT7-Ki-IlWR-0g.png" /><figcaption>Gemini generated image</figcaption></figure><p>Have you ever tried to set up a local Kubernetes cluster? Or try to understand what cloud providers set up for us when we subscribe to an offer?</p><p>Let me introduce you to how I set up a local Kubernetes cluster to play with it. What challenges did I face? And how I solved them.</p><h4>Computer setup</h4><p>Ok before to start, some information about my computers setup:</p><ul><li>Fedora 43/44</li><li>Intel Core i7/i9</li><li>32Go RAM</li></ul><blockquote><strong><em>Disclaimer</em></strong>: <em>All command lines will be for Fedora, but most of them are Linux-based anyway.</em></blockquote><h4>Begin the installation.</h4><p>Now that the foundation is set, let’s dive into creating the cluster.</p><p>Fedora provides <a href="https://docs.fedoraproject.org/en-US/quick-docs/using-kubernetes-kubeadm/">official documentation</a> to guide you through the initial setup. However, their guide relies on Kubernetes version 1.32, which is now deprecated. The currently supported versions are 1.33 through 1.36 (with 1.36 having just been released on April 22, 2026).</p><p>To get the best of both worlds, use the official Fedora documentation for the basic machine preparation, and then follow this article to resolve version-specific issues. If you choose to use Fedora’s guide but want to install the latest versions from binaries, this article provides the essential tips you’ll need to succeed.</p><h4>Problems encountered.</h4><p>Before version 1.33, the Fedora documentation setup was flawless. Everything worked out of the box — it was essentially an “execute commands and run” kind of deal.</p><p>But when 1.33 dropped, a “minor” bug appeared that caused massive headaches, specifically with internal cluster networking. By default, the setup is supposed to automatically map out the network interface used by the Container Network Interface (CNI) — you can check out the [<a href="https://www.cni.dev/">CNI standard here</a>] for the technical details.</p><p>Let’s be real: networking is nobody’s favorite topic, and if it breaks, you’re completely stuck. Usually, the network interface is spun up automatically when you install the binaries. But lately, it sometimes fails to create itself. The cluster will still try to boot, but it gets hopelessly stuck on that missing network piece.</p><h3>How to identify a network problem?</h3><p>If you tail the logs using the following command:</p><pre>journalctl -f -u kubelet</pre><p>You’ll likely spot an error that looks like something like this:</p><pre>error adding pod kube-system_coredns-7d764666f9-8lcn8 <br>to CNI network \&quot;cbr0\&quot;: plugin type=\&quot;flannel\&quot; failed (add): <br>failed to load flannel &#39;subnet.env&#39; <br>file: open /run/flannel/subnet.env: no such file or directory. <br>Check the flannel pod log for this node.<br>&quot; pod=&quot;kube-system/coredns-7d764666f9-8lcn8&quot;</pre><p>Or, if the configuration is clashing, you might see this instead:</p><pre>plugin type=\&quot;flannel\&quot; failed (add): failed to set bridge addr: <br>\&quot;cni0\&quot; already has an IP a&gt;<br>dcdff2c4)\\\&quot;: rpc error: code = Unknown desc = <br>failed to create pod network sandbox k8s_exxxx&gt;<br>I network \&quot;cbr0\&quot;: plugin type=\&quot;flannel\&quot; failed (add): <br>failed to set bridge addr: \&quot;cni0\&quot; already has an <br>IP address different from 10.244.0.1/24&quot;</pre><p>Broadly speaking, the error is telling you that the network bridge meant to handle traffic between your pods and the cluster is broken or wasn’t created properly.</p><p>To see what’s going on under the hood, take a look at the configuration files inside /etc/cni/net.d. Normally, you should see files like:</p><ul><li><em>100-crio-bridge.conflist</em></li><li><em>200-loopback.conflist</em></li><li><em>10-flannel.confli</em>st</li></ul><p>Here is what I have in my case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*d8m-jdfWo0Hc-knJla4hag.png" /></figure><p>In the following file you should have something like this:</p><p><em>10-crio-bridge.configlist</em>:</p><pre>{<br>  &quot;cniVersion&quot;: &quot;1.0.0&quot;,<br>  &quot;name&quot;: &quot;crio&quot;,<br>  &quot;plugins&quot;: [<br>    {<br>      &quot;type&quot;: &quot;bridge&quot;,<br>      &quot;bridge&quot;: &quot;cni0&quot;,<br>      &quot;isGateway&quot;: true,<br>      &quot;ipMasq&quot;: true,<br>      &quot;hairpinMode&quot;: true,<br>      &quot;ipam&quot;: {<br>        &quot;type&quot;: &quot;host-local&quot;,<br>        &quot;routes&quot;: [<br>            { &quot;dst&quot;: &quot;0.0.0.0/0&quot; },<br>            { &quot;dst&quot;: &quot;::/0&quot; }<br>        ],<br>        &quot;ranges&quot;: [<br>            [{ &quot;subnet&quot;: &quot;10.85.0.0/16&quot; }],<br>            [{ &quot;subnet&quot;: &quot;1100:200::/24&quot; }]<br>        ]<br>      }<br>    }<br>  ]<br>}</pre><p><em>10-flannel.configlist</em>:</p><pre>{<br>  &quot;name&quot;: &quot;cbr0&quot;,<br>  &quot;cniVersion&quot;: &quot;0.3.1&quot;,<br>  &quot;plugins&quot;: [<br>    {<br>      &quot;type&quot;: &quot;flannel&quot;,<br>      &quot;delegate&quot;: {<br>        &quot;hairpinMode&quot;: true,<br>        &quot;isDefaultGateway&quot;: true<br>      }<br>    },<br>    {<br>      &quot;type&quot;: &quot;portmap&quot;,<br>      &quot;capabilities&quot;: {<br>        &quot;portMappings&quot;: true<br>      }<br>    }<br>  ]<br>}</pre><p>For more details please refer to the official <a href="https://www.cni.dev/plugins/current/main/bridge/">documentation</a>.</p><p>By configuring this file, we explicitly define the network interface that the cluster will use to communicate with and route traffic to the pods.</p><h3>Network interfaces.</h3><p>Linux provides the flexibility to create, modify, or edit network interfaces as required. We start by listing the currently active interfaces. The following command will display all network configurations:</p><pre>ip -a a<br># generating something like that:<br>1 : lo: &lt;LOOPBACK,UP,LOWER_UP&gt; mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000<br>    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00<br>    inet 127.0.0.1/8 scope host lo<br>       valid_lft forever preferred_lft forever<br>    inet6 ::1/128 scope host noprefixroute <br>       valid_lft forever preferred_lft forever<br>2: eno2: &lt;NO-CARRIER,BROADCAST,MULTICAST,UP&gt; mtu 1500 qdisc mq state DOWN group default qlen 1000<br>    link/ether c8:7f:54:04:d3:c6 brd ff:ff:ff:ff:ff:ff<br>    altname enp8s0<br>    altname enxc87f5404d3c6<br>3: wlp0s20f3: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1500 qdisc noqueue state UP group default qlen 1000<br>    link/ether 06:2a:a3:3c:93:bf brd ff:ff:ff:ff:ff:ff permaddr 70:1a:b8:33:1d:5a<br>    altname wlx701ab8331d5a<br>    inet 192.168.1.35/24 brd 192.168.1.255 scope global dynamic noprefixroute wlp0s20f3<br>       valid_lft 82906sec preferred_lft 82906sec<br>    inet6 2a01:cb19:c87:3500:832e:f40a:1b2e:b1de/64 scope global dynamic noprefixroute <br>       valid_lft 86355sec preferred_lft 555sec<br>    inet6 fe80::88e2:500c:99b7:32f4/64 scope link noprefixroute <br>       valid_lft forever preferred_lft forever<br># rest of the interfaces available<br># ...</pre><p>The cni0 interface might already be configured:</p><pre>XXX: cni0: &lt;NO-CARRIER,BROADCAST,MULTICAST,UP&gt; mtu 1500 qdisc noqueue state DOWN group default qlen 1000<br>    link/ether f2:27:38:ee:c6:1a brd ff:ff:ff:ff:ff:ff<br>    inet 10.85.0.0/25 brd 10.85.0.127 scope global noprefixroute cni0<br>       valid_lft forever preferred_lft forever<br>    inet 10.85.0.0/24 brd 10.85.0.255 scope global noprefixroute cni0<br>       valid_lft forever preferred_lft forever</pre><p>If the interface does not exist, use this nmcli command to add it:</p><pre>sudo nmcli connection add con-name cni0 connection.id cni0 \<br>ifname cni0 type bridge ipv4.addresses 10.244.0.1/24 \<br>connection.interface-name cni0 \<br>connection.metered true ipv4.method manual</pre><p>And we can check that the connection is created:</p><pre>nmcli<br># and the output<br>cni0: connected to cni0<br>        &quot;cni0&quot;<br>        bridge, 8E:50:47:76:41:46, sw, mtu 1450<br>        inet4 10.244.0.1/24<br>        route4 10.244.0.0/24 metric 425</pre><p>Note that this configuration is temporary; it will be lost upon reboot. To make the settings permanent, use the following commands:</p><pre># up the connection<br>sudo nmcli connection up cni0<br># make the save of the connection<br>sudo nmcli -e con save cni0</pre><h3>Check that the modifications are applied.</h3><p>Restart the CRIOservice and the cluster.</p><pre>sudo systemctl restart crio.service</pre><p>For kubelet.service, you may need to terminate existing processes before restarting the service. This ensures a clean state and allows the service to apply your configuration changes.</p><pre>#stop/kill the service<br>sudo systemctl stop kubelet.service<br><br>#snipet to kill all processes<br>for pid in $(ps aux | grep kube | awk &#39;{print $2}&#39;); do sudo kill -9 $pid; done;<br>sudo systemctl restart kubelet.service</pre><p>If everything is fine, all the pods should be started and running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udt9CATDJLcrwuaRLWKr6A.png" /></figure><p>All pods can now run on the cluster without errors. Kubernetes networking is critical to cluster health — it enables communication between all nodes and must function correctly.</p><p>Future articles will cover other networking issues you may face, while monitoring metrics remain essential for scaling your deployments.</p><p>This concludes the guide. I hope it has deepened your understanding of the under-the-hood processes involved in provisioning a complete Kubernetes cluster from scratch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cdae6ef62a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JPA and inheritance with Hibernate.]]></title>
            <link>https://medium.com/@tahitoa.merlin/jpa-and-inheritance-with-hibernate-341f51e3f2fc?source=rss-e186e579e9d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/341f51e3f2fc</guid>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Tahitoa Merlin]]></dc:creator>
            <pubDate>Fri, 30 Jan 2026 00:21:53 GMT</pubDate>
            <atom:updated>2026-01-30T00:23:34.683Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered what inheritance looks like from the JPA entities to the database?</p><p>Let me introduce you to the inheritance, when you generate the database schema from your entities, and how it looks from a database perspective.</p><p>Also, what are the advantages and inconveniences when you make the same kind of inheritance from the POO and the database?</p><p>Ok, the context is now clear; let’s talk about the technical stack used:</p><ul><li>JDK 25</li><li>SpringBoot 4</li><li>Hibernate 7.2</li><li>MariaDB for the database</li></ul><p><strong><em>DISCLAIMER: the names may differ from the code.</em></strong></p><h3>Declaration of inheritance from the JPA perspective.</h3><p>But how to represent the inheritance of the entities that will be translated to the database from the JPA perspective? To do it we use the <em>@Inheritance</em> annotation. And it looks like this:</p><pre>@Entity<br>@Inheritance(strategy = InheritanceType.XXX)<br>public abstract class ParentEntity {<br>//declaration of properties<br>}</pre><p>For this article we’ll take the 2 following samples:</p><ul><li>The inheritance with the @Inheritance with join strategy</li><li>The inheritance with the @Inheritance table per class strategy</li></ul><p>And the model looks like this:</p><ul><li>From the POO point of view:</li></ul><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*1ZRGUgRKTleiDngz.png" /></figure><p>Generated from mermaidonline.live</p><ul><li>From the database point of view:</li></ul><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*vdcbmzduyJX1tBgF.png" /></figure><p>Generated from mermaidonline.live</p><p>So here are the bases. It’s very simple, and for the moment it misses one entity to use the whole thing with the relationships between the entities.</p><h3>What is the purpose of the inheritance for JPA?</h3><p>Inheritance is a common concept in POO, as it permits sharing properties and behavior from the parent to the child. We have commonly seen something like that:</p><pre>public abstract class Animal {<br>  protected String name;<br>  protected Integer age;</pre><pre>  public abstract void makeSound();</pre><pre>  //boilerplate code<br>}</pre><pre>public class Dog extends Animal {<br>  @Override<br>  public void makeSound() {<br>    System.out.println(&quot;bark&quot;);<br>  }<br>}</pre><pre>public class Cat extends Animal {<br>  @Override<br>  public void makeSound() {<br>    System.out.println(&quot;meow&quot;);<br>  }<br>}</pre><p>Well, when we design entities, this concept still applies by sharing common columns (most of the time) or common actions between entities.</p><h3>JPA entity definitions for the JOIN strategy.</h3><p>For this strategy let’s take the following sample:</p><pre>@Entity<br>@Table(name = &quot;parent&quot;)<br>@Inheritance(strategy = InheritanceType.JOINED)<br>@Getter<br>@Setter<br>public abstract class ParentEntity {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    @Column(name = &quot;name&quot;)<br>    private String name;<br>}<br><br>@Entity<br>@Table(name = &quot;direct_child_one&quot;)<br>@DiscriminatorValue(&quot;CHILD_ONE&quot;)<br>@Setter<br>@Getter<br>public class DirectChildOne extends ParentEntity{<br>    @Column(name = &quot;child_one_name&quot;)<br>    private String childOneName;<br>    @Column(name = &quot;property_one&quot;)<br>    private String propertyOne;<br>}<br>@Entity<br>@Inheritance(strategy = InheritanceType.JOINED)<br>@Getter<br>@Setter<br>public abstract class SubParent extends ParentEntity {<br>    @OneToMany(mappedBy = &quot;subParent&quot;)<br>    private List&lt;RelationEntity&gt; relations = new ArrayList&lt;&gt;();<br>}<br>@Entity<br>@DiscriminatorValue(&quot;SUB_CHILD_ONE&quot;)<br>@Setter<br>@Getter<br>public class SubChildOne extends SubParent{<br>    @Column(name = &quot;sub_child_one_name&quot;)<br>    private String subChildOneName;<br>    @Column(name = &quot;sub_price&quot;)<br>    private Double subPrice;<br>}</pre><p>These entities are the entities designed from the MERMAID diagram (see above). They are simple, but not the annotations used to define them.</p><p>And concretely it looks like this when the schema is generated from Hibernate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/0*Fh9Vb3R6xS02CV9p.png" /></figure><p>Tables generated from the JPA entities</p><h3>Let’s take a closer look.</h3><p>As the Java entities are designed to be in a JOINED strategy, the database reflects the same inheritance, so if we take the sub_parent table, it contains only 1 column that is a PK and a FK (of the parent table).</p><p>We have a true inheritance, same as the POO design. So it’s cool; we have reproduced the same structure defined by the code.</p><p>But we didn’t see how to use this inheritance yet; let’s take the following entity:</p><pre>@Entity<br>@Table(name = &quot;relation&quot;)<br>@Getter<br>@Setter<br>public class RelationEntity {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    @Column(name = &quot;name&quot;)<br>    private String name;<br>    @Column(name = &quot;price&quot;)<br>    private Double price;<br>    @Column(name = &quot;type&quot;)<br>    private String type;<br>    @ManyToOne<br>    private SubParent subParent;<br>}</pre><p>In this entity we clearly define a @ManyToOne relationship; it implies that any child of the SubParent entity can be the association of this entity.</p><p>It’s simple, and it works perfectly. But what happens when we save/fetch this entity? Let’s take a look at the queries performed.</p><h3>The truth behind this inheritance.</h3><p>In the case of a direct child (Parent &lt;- DirectChildOne), when we persist the child, we have the following SQL queries executed:</p><pre>Hibernate: insert into parent (name) values (?)<br>Hibernate: insert into direct_child_one (child_one_name,property_one,id) values (?,?,?)</pre><p>We have two queries executed. Because we have to insert in the parent table, which holds the true data, and in the direct_child_one table that holds some specific properties with the ID, which is the FK of the parent table.</p><p>And what happens when we persist a SubChildOne entity? If you have followed correctly, you will have the following SQL queries executed:</p><pre>Hibernate: insert into parent (name) values (?)<br>Hibernate: insert into sub_parent (id) values (?)<br>Hibernate: insert into sub_child_one (sub_child_one_name,sub_price,id) values (?,?,?)</pre><p>Yep, 3 queries, and the explanation is the same: the parent table holds the true data information, the sub_parent table is clearly the representation of the inheritance in the database, and the sub_child_one table is the true persisted entity.</p><p>I let you imagine what happens if you have a complex inheritance design through your entities and directly represented in the database…</p><p>And concretely, what happens when we fetch the data? Well, if for any reason we activated the EAGER fetch, the N+1 problem will occur, and if we look at the JPQL query, we just have a long query executed, and it’s a bit weird:</p><pre>Hibernate: select sp1_0.id,<br>case when sp1_1.id is not null then 3 end,<br>sp1_2.name,sp1_1.sub_child_one_name,sp1_1.sub_price,r1_0.sub_parent_id,<br>r1_0.id,r1_0.name,r1_0.price,r1_0.type <br>from sub_parent sp1_0 left <br>join sub_child_one sp1_1 on sp1_0.id=sp1_1.id <br>join parent sp1_2 on sp1_0.id=sp1_2.id left <br>join relation r1_0 on sp1_0.id=r1_0.sub_parent_id <br>where sp1_0.id=?</pre><p>Don’t forget that the current sample is a Parent =&gt; +1 child.</p><p>I let you imagine the performance issue when the tables contain thousands rows and multiple layers of inheritance.</p><p>So yes, it’s convenient, and it works, but if you need to model something like this, the troubles will occur when the volume of data grows.</p><h3>Can we perform the same logic with the TABLE_PER_CLASS strategy?</h3><p>We can clearly change the strategy to TABLE_PER_CLASS and adapt a bit of the code to be compliant with the JPA specifications. And the diagrams now should look like this:</p><p>From this strategy we will have the following diagrams:</p><ul><li>Entities design diagram:</li></ul><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*4zFxjKlNUmpSxkDv.png" /></figure><p>Generated from mermaidonline.live</p><ul><li>Database design diagram:</li></ul><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*md1IsDR1GpDRxBNK.png" /></figure><p>Generated from mermaidonline.live</p><p>Take a closer look at the tables generated; the property name of ParentEntity is present in all tables, so the inheritance has been applied correctly. Two tables have been deleted: parent and sub_parent.</p><p>Also, the ID column is now a sequence, as the parent entity cannot apply the IdentityType.IDENTITY to generate the IDs.</p><p>As we can see, the logic is not the same; we have to modify the relationships between the entities, as the database cannot hold multiple foreign keys on the same column. Even though we can still query the relation entities with their relationships.</p><h3>The traps to avoid.</h3><p>Where things start to be complicated are the following statements:</p><ul><li>Try to fetch the upper parent (that is abstract but can be fetched) with its relationships (<strong><em>MultipleBagFetchException</em></strong>).</li><li>Try to fetch by FetchType.EAGER attribute: if the relationships are very small, it can work without too many performances impacts.</li></ul><h3>Another way to define inheritance.</h3><p>The JPA specification gives us some tools to make inheritance; with the @MappedSuperClass, we can define an abstract class that holds all the attributes to put in the database.</p><p>The only problem is that we cannot reference it in the different entities for the relationships, as this class is not a table. This iswhere the @Inheritance annotation is useful, but it should be designed carefully.</p><h3>Last tips.</h3><p>Always try to design the database as a first step, then generate the entities from this model (with software, from a UML diagram, etc.).</p><p>By designing the database from the entities, you’ll just make the database coherent from the code; but from the code can be awkward or misconceived.</p><p>And the best part is when you inherit it from a legacy project, you see all the problems, but touching is risky and before moving anything make a good analysis and think of:</p><ul><li>How to make the migration from the existing legacy to the model?</li><li>Am I able to fetch all the data to migrate them?</li><li>How much time does it take?</li><li>Does there exist any tests (unit tests, integration tests, E2E)?</li></ul><p>By experience, when the model is very complex (with a lot of relationships, inheritances, etc.), it’s very hard to estimate and refactor/move entities (because touching one entity implies to touching/refactoring 20 others).</p><p>Good advice: take the time, do some retro-engineering and test the application (and not only from the unit test perspective).</p><p>That’s all for today; you can find all the code and diagrams related to this article in this repository: <a href="https://github.com/maequise/articles">link here</a> in <strong><em>jpa-inheritance</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=341f51e3f2fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JPA and inheritance with Hibernate.]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@tahitoa.merlin/jpa-and-inheritance-with-hibernate-f83719131a94?source=rss-e186e579e9d3------2"><img src="https://cdn-images-1.medium.com/max/2600/1*Swl5ze5a3ShYHC7efCpRhQ.png" width="2705"></a></p><p class="medium-feed-snippet">Have you ever wondered what inheritance looks like from the JPA entities to the database?</p><p class="medium-feed-link"><a href="https://medium.com/@tahitoa.merlin/jpa-and-inheritance-with-hibernate-f83719131a94?source=rss-e186e579e9d3------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@tahitoa.merlin/jpa-and-inheritance-with-hibernate-f83719131a94?source=rss-e186e579e9d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f83719131a94</guid>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Tahitoa Merlin]]></dc:creator>
            <pubDate>Fri, 30 Jan 2026 00:20:16 GMT</pubDate>
            <atom:updated>2026-01-30T00:22:28.748Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Create custom JUnit 5/6 extension]]></title>
            <link>https://medium.com/@tahitoa.merlin/create-custom-junit-5-6-extension-a8d96b6b0d08?source=rss-e186e579e9d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8d96b6b0d08</guid>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-craftmanship]]></category>
            <category><![CDATA[junit-5]]></category>
            <dc:creator><![CDATA[Tahitoa Merlin]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 07:44:34 GMT</pubDate>
            <atom:updated>2025-11-10T07:45:44.702Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*NWtxu_n3yT_QJk_7yIEhTQ.png" /><figcaption>AI generated image (Claude Sonnet)</figcaption></figure><p>Hey folks! It’s been a while, as I always write something when I find something useful or even tricky; it can take time between articles.</p><p>Anyway! Let’s talk about the JUnit extension system. I think that anyone has already used it, without knowing what happens under the hood, nor trying to understand how the extension used work.</p><h4>Sample of extension, and its usage</h4><p>Let’s take this piece of code, simple and realistic:</p><pre>@ExtendWith(SpringExtension.class)<br>class MySuperTest {<br>  @Autowired<br>  private MyCoolService service;<br><br>  @BeforeEach<br>  void setup() {<br>    //do something<br>  }<br><br>  @Test<br>  void superTest() {<br>    //do the test<br>  }<br>}</pre><p>So here’s what happened? Let’s break it (general purpose):</p><ul><li>Telling the test class to use the JUnit’s SpringExtension</li><li>Injecting a service in the test class</li><li>Do the test with injected service</li></ul><p>By doing this, the test class loads and setup a Spring context, which is in charge of the dependency container injection. So when the test is loaded and initialised it’s create a spring context, and then the service field is injected with the corresponding bean matching the type of the class member.</p><h4>Sample of usage.</h4><p>Writing tests with faked data can be long and annoying, declaring the variable, instantiating the class to populate, using the setters or, if a record set, all the values, etc.</p><p>Let’s say it: “Oh God! Please! Kill me!”</p><p>That’s where I found a lib, while reading an article on faking data without the usage of setters or constructors. Something like Mockito, and this lib is <em>EasyRandom </em>and can be found <a href="https://github.com/j-easy/easy-random">here</a>, but let’s take this piece of code:</p><pre>class FakedDataTest {<br>  private EasyRandom populator;<br><br>  @BeforeEach<br>  void setup() {<br>    //setup for each test<br>  }<br><br>  @Test<br>  void myCoolTest() {<br>    var dto = populator.nextObject(MyDto.class);<br>    <br>    //do assertions<br>  }<br>}</pre><p>Ok, it’s simple, concise and clear, but the lib can be configured to exclude some fields of the faked class.</p><p>But that exclusion can only be made at the creation of the instance, and not after, and to do that, we have something like that:</p><pre>class FakedDataTest {<br>  private EasyRandom populator;<br>  <br>  @BeforeEach<br>  void setup() {<br>    var parameters = new EasyRandomParameters()<br>                      .excludeFields(FieldPredicates.named(&quot;someField&quot;));<br><br>    populator = new EasyRandom(parameters);<br>  }<br>  <br>  @Test<br>  void myCoolTest() {<br>    var dto = populator.nextObject(MyDto.class);<br>    <br>    assertNull(dto.getSomeField());<br>    //do other assertions<br>  }<br>}</pre><p>Again, it’s simple, concise and clear. But what happens if you have to customize the populator for a specific test? Or for different tests?</p><p>The library enforces the immutability of the populator, so you can’t add/remove fields from the exclusion of the generator unless you create a specific instance for the tests.</p><h4>The JUnit extension to the rescue.</h4><p>Imagine that you have to setup the populator on the fly for a specific test; by just using an annotation, seems perfect, right?</p><p>By creating a custom extension, the dream becomes a reality!</p><p>Let’s take the previous examples and change them to something like that:</p><pre>@ExtendWith(PopulatorExtension.class)<br>class FakedDataTest {<br>  private EasyRandom populator;<br><br>  @BeforeEach<br>  void setup() {<br>     populator = new EasyRandom();<br>  }<br>  <br>  @Test<br>  void myCoolTest_no_exclusion() {<br>    var dto = populator.nextObject(MyDto.class);<br>   <br>    //do assertions<br>  }<br><br>  @Test<br>  void myCoolTest_exclude_field(@Populator(excludedFields= {&quot;someField&quot;}) EasyRandom populatorCustom) {<br>    var dto = populatorCustom.nextObject(MyDto.class);<br>    <br>    assertNull(dto.getSomeField());<br>    //do other assertions<br>  }<br>}</pre><p>It’s clean and lean; the general populator is used for all fields to be faked, and in the second, for some reasons, I need to exclude the <em>someField</em> field from the faked data.</p><p>But we clearly see that the code has changed by adding the</p><ul><li>@ExtendWith annotation</li><li>@Populator custom annotation</li></ul><p>As always, nothing happens magically! Under the hood, the JUnit processing of annotations performs the real magic!</p><p>But what happens in that extension and with this @Populator annotation?</p><p>The Populator annotation is simple and looks like that:</p><pre>@Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD})<br>@Retention(RetentionPolicy.RUNTIME)<br>public @interface Populator {<br>    /// List all the fields that should be excluded from the random populator<br>    String[] excludeFields() default {};<br>}</pre><p>Nothing fancy! Just declaring on which elements it’s declarable, the type of retention, and a field to declare potential fields to exclude from the generator.</p><p>What about the extension itself? That’s where the magic is hidden:</p><pre>public class PopulatorExtension implements TestInstancePostProcessor, BeforeAllCallback, ParameterResolver {<br>    /// used to instantiate the class fields that are static    <br>    @Override<br>    public void beforeAll(ExtensionContext context) throws Exception {<br>        var testClass = context.getRequiredTestClass();<br>        injectFields(testClass, null, ModifierSupport::isStatic);<br>    }<br><br>    /// used to instantiate the class fields that are not static<br>    @Override<br>    public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception {<br>        var testClass = context.getRequiredTestClass();<br>        injectFields(testClass, testInstance, ModifierSupport::isNotStatic);<br>    }<br><br>    @Override<br>    public boolean supportsParameter(ParameterContext parameterContext,<br>                                     ExtensionContext extensionContext) throws ParameterResolutionException {<br>        return parameterContext.isAnnotated(Populator.class) &amp;&amp; isPopulatorTypeClass(parameterContext.getParameter().getType());<br>    }<br><br>    /// this method is used for the parameters in test methods<br>    @Override<br>    public Object resolveParameter(ParameterContext parameterContext,<br>                                   ExtensionContext extensionContext) throws ParameterResolutionException {<br>        return processMethodParameter(parameterContext);<br>    }<br><br>    /// instantiate the populator for the field that is processing<br>    private void injectFields(Class&lt;?&gt; testClass, @Nullable Object testInstance, Predicate&lt;Field&gt; predicate) {<br>        findAnnotatedFields(testClass, predicate)<br>                .forEach(field -&gt; {<br>                    field.setAccessible(true);<br>                    try {<br>                        field.set(testInstance, processField(field));<br>                        field.setAccessible(false);<br>                    }catch (IllegalAccessException e) {<br>                       throw new RuntimeException(e); //throw a runtime exception to kill the test<br>                    }<br>                });<br>    }<br><br>    private EasyRandom processMethodParameter(ParameterContext parameterContext) {<br>        var parameters = processMetadata(parameterContext.findAnnotation(Populator.class).get());<br>        return new EasyRandom(parameters);<br>    }<br><br>    private EasyRandom processField(Field field) {<br>        Populator metadata = field.getAnnotation(Populator.class);<br>        var parameters = processMetadata(metadata);<br>        return new EasyRandom(parameters);<br>    }<br><br>    /// This the main method of the extension<br>    /// It processes the annotation and create the [EasyRandomParameters] object that is used later for the creation<br>    /// of the randomizer<br>    /// @return [EasyRandomParameters] that matches the metadata of the annotation<br>    private EasyRandomParameters processMetadata(Populator annotation) {<br>        var parameters = new EasyRandomParameters();<br>        //check and set all the fields that must be excluded from the fake date generated<br>        for (String excludeField : annotation.excludeFields()) {<br>            parameters.excludeField(FieldPredicates.named(excludeField));<br>        }<br>        return parameters;<br>    }<br><br>    private boolean isPopulatorTypeClass(Class&lt;?&gt; type) {<br>        return type != null &amp;&amp; type.isAssignableFrom(EasyRandom.class);<br>    }<br>    /// Retrieve all fields of the test class instance<br>    /// also apply a [Predicate] to know if the field matches the pre-required<br>    /// @return a [Stream] of fields<br>    private Stream&lt;Field&gt; findAnnotatedFields(Class&lt;?&gt; testClass, Predicate&lt;Field&gt; predicate) {<br>        return Arrays<br>                .stream(testClass.getDeclaredFields())<br>                .filter(field -&gt; field.getAnnotation(Populator.class) != null &amp;&amp; predicate.test(field));<br>    }<br>}</pre><p>Ok, as we can see, the extension class contains all the logic to apply when a test uses this extension.</p><p>The extension is clearly reflection oriented, we check for declared fields, if they are annotated, etc.</p><p>But the instantiation of EasyRandom instance is “normal”; no reflection, just the usage of the constructor, and if needed, the creation of an instance with custom parameters to control how the generator works.</p><p>The extension is not perfect and needs to be reworked and improved, but it responds to specific needs at specific moments in the project life.</p><p>Thanks for the reading, and I’ll see you next time for another great — or not, you’re the judges — article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8d96b6b0d08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create custom JUnit 5/6 extension]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@tahitoa.merlin/create-custom-junit-5-6-extension-9c1c105d7769?source=rss-e186e579e9d3------2"><img src="https://cdn-images-1.medium.com/max/800/1*NWtxu_n3yT_QJk_7yIEhTQ.png" width="800"></a></p><p class="medium-feed-snippet">Hey folks! It&#x2019;s been a while, as I always write something when I find something useful or even tricky; it can take time between articles.</p><p class="medium-feed-link"><a href="https://medium.com/@tahitoa.merlin/create-custom-junit-5-6-extension-9c1c105d7769?source=rss-e186e579e9d3------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@tahitoa.merlin/create-custom-junit-5-6-extension-9c1c105d7769?source=rss-e186e579e9d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c1c105d7769</guid>
            <category><![CDATA[software-craftmanship]]></category>
            <category><![CDATA[junit-5]]></category>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Tahitoa Merlin]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 07:41:39 GMT</pubDate>
            <atom:updated>2025-11-10T07:45:12.283Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Spring Batch — PropertiesLauncher usage of external properties file.]]></title>
            <link>https://medium.com/@tahitoa.merlin/spring-batch-propertieslauncher-usage-of-external-properties-file-2382e44af099?source=rss-e186e579e9d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2382e44af099</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-batch]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Tahitoa Merlin]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 16:18:08 GMT</pubDate>
            <atom:updated>2025-08-31T16:20:16.732Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Batch — PropertiesLauncher usage of external properties file.</h3><p>Hey folks, it’s been a while! Let me share with you what made me crazy for hours and tests using external file properties when I tried to launch some batches from the command line with the <em>PropertiesLauncher</em>.</p><h4>Context</h4><p>Here is the stack used:</p><ul><li>Spring Boot 3.5.x</li><li>JDK 24</li><li>Spring Batch 5.2.x</li></ul><p>And all of this is launched through the <em>PropertiesLauncher</em> (the solution will also work for the <em>CommandLineJobRunner</em>) from a service deployed on the VM.</p><p>By default the Spring Batch application will scan the <em>classpath</em> of the <em>jar</em> to load the <em>application.properties</em> file.</p><p>But what happens if you want to externalise the <em>properties</em> to use? Or if you remove any <em>*.properties</em> file from the package?</p><h4>What I tried to make it works?</h4><p>As Spring Boot gives the possibility to launch the application with some properties to load external properties from files, I tried to pass the file properties when the batch was launched.</p><p>So I tried all that kind of property in the command line:</p><ul><li><em>spring.config.location</em></li><li><em>loader.path/loader.home/loader.config.location</em></li><li><em>spring.config.import</em></li></ul><p>What I found is that passing the property directly with:</p><pre>java -jar my-application.jar --my.property=value</pre><p>works perfectly. The property is injected correctly and interpreted in the configuration/beans classes.</p><h4>So what was the solution I used?</h4><p>Have you ever heard of <em>PropertySourcesPlaceholderConfigurer</em>? Most of the time this bean is auto-configured, so we rarely customize it.</p><p>But in our case, this is the perfect solution, as it permits us to load some properties and inject them into the context, making them available to use in the application context.</p><p>And here’s how I used it:</p><pre>@Configuration<br>public class PropertiesConfiguration {<br>    @Bean<br>    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(Environment env) throws Exception {<br>        var props = new Properties();<br>        var pathOfPropertiesFile = env.getProperty(&quot;spring.config.location&quot;, &quot;classpath:application.properties&quot;);</pre><pre>        props.load(new FileInputStream(pathOfPropertiesFile));</pre><pre>        var e = new PropertySourcesPlaceholderConfigurer();</pre><pre>        //inject the properties in the context<br>        e.setProperties(props);</pre><pre>        return e;<br>    }</pre><pre>}</pre><p>So now, we know the system property name to use with the path of the properties file, and we can now launch the batch with the following command line:</p><pre>java -Dspring.config.location=/path/to/file.properties -jar my-app.jar</pre><p>Everything works now perfectly; the properties are loaded perfectly. If you need to load more than 1 file, edit the code to split files separated with a comma.</p><p>It should look like something like this:</p><pre>@Configuration<br>public class PropertiesConfiguration {<br>    @Bean<br>    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(Environment env) throws Exception {<br>        var props = new Properties();<br>        //by default search in the classpath for the application.properties file<br>        var pathOfPropertiesFile = env.getProperty(&quot;spring.config.location&quot;, &quot;classpath:application.properties&quot;);</pre><pre>        Arrays.stream(pathOfPropertiesFile.split(&quot;,&quot;)).forEach(path -&gt; {<br>            try {<br>                props.load(new FileInputStream(pathOfPropertiesFile));<br>            } catch (IOException e) {<br>                throw new RuntimeException(e);<br>            }<br>        });</pre><pre>        var e = new PropertySourcesPlaceholderConfigurer();</pre><pre>        //inject the properties in the context<br>        e.setProperties(props);</pre><pre>        return e;<br>    }<br>}</pre><p>I was very surprised that the casual way to load a properties file is non-functional, but as always, the Spring framework gives some tricks to perform what we need to do, and with a minimal amount of code.</p><p>And that’s all for today. I hope I gave you some solutions to common problems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2382e44af099" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Batch — PropertiesLauncher usage of external properties file.]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">Hey folks, it&#x2019;s been a while! Let me share with you what made me crazy for hours and tests using external file properties when I tried to&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@tahitoa.merlin/spring-batch-propertieslauncher-usage-of-external-properties-file-1afb11d64e70?source=rss-e186e579e9d3------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@tahitoa.merlin/spring-batch-propertieslauncher-usage-of-external-properties-file-1afb11d64e70?source=rss-e186e579e9d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1afb11d64e70</guid>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[spring-batch]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Tahitoa Merlin]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 16:16:56 GMT</pubDate>
            <atom:updated>2025-08-31T16:19:59.784Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How did a simple best practice make Hibernate happy?]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">Hey guys, let me tell you a story where the best practice of defining a POJO/DTO in Java and Hibernate ORM (6.6.x+) met.</p><p class="medium-feed-link"><a href="https://medium.com/@tahitoa.merlin/how-did-a-simple-best-practice-make-hibernate-happy-4d65a4c37dad?source=rss-e186e579e9d3------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@tahitoa.merlin/how-did-a-simple-best-practice-make-hibernate-happy-4d65a4c37dad?source=rss-e186e579e9d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d65a4c37dad</guid>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[spring-boot-3]]></category>
            <dc:creator><![CDATA[Tahitoa Merlin]]></dc:creator>
            <pubDate>Sat, 31 May 2025 10:23:56 GMT</pubDate>
            <atom:updated>2025-05-31T10:23:56.285Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Spring Batch and concurrency]]></title>
            <link>https://medium.com/@tahitoa.merlin/spring-batch-and-concurrency-664cb7c6ea1b?source=rss-e186e579e9d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/664cb7c6ea1b</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-batch]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[concurrency-in-java]]></category>
            <dc:creator><![CDATA[Tahitoa Merlin]]></dc:creator>
            <pubDate>Fri, 02 May 2025 19:12:07 GMT</pubDate>
            <atom:updated>2025-05-02T19:12:07.031Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSrtFHRd2zz6P9BfvR2yew.png" /><figcaption>Generated with ChatGPT</figcaption></figure><p>Hey folks! It’s been a while, but I always share when I’m facing technical issues that can be common but tricky to solve, or when the solutions found on topics don’t solve the issue.</p><h4>Context</h4><p>Let’s put some context with the current stack used:</p><ul><li>JDK 24 (not limited to using an LTS version but not using the experimental features)</li><li>Spring Boot 3.4.4 (the latest version, 3.4.5, causes some issues with Hibernate)</li><li>Spring Batch 5.2.2 (linked to the Spring Boot version)</li></ul><p>Let’s say it’s a common stack and nothing really fancy.</p><h4>Problem</h4><p>Well, actually, the application is a legacy application (created like 10+ years ago), used to create/setup some contracts and make the billing.</p><p>Actually, the billing process is done in some batches; the generated data represents, like, ~17k lines of billing. Not too much; it’s a little data volumetry.</p><p>But to generate that number of lines, it took a good average of 15 hours. Kind of incredible!</p><p>But I found the root cause: the database model was generated by Hibernate/JPA, so it’s like a good piece of shit. I discovered that the inheritance is possible in the database, thanks to that project.</p><h4>First solution imagined</h4><p>Most of the time, when you face some performance problems, you try to solve the root cause; here the root cause is the database model and the JPA queries. Refactoring the database model is a huge amount of work, making everything dangerous. The JPA queries could be migrated to raw SQL queries, but it implies that you can find all the data through the raw SQL queries. How to say that… Hibernate seems to be able to; I was not.</p><p>So when you can’t solve the root cause directly, and the situation continues to be degraded, you scale up the process in a micro-services architecture easily. In a monolithic architecture… You’re able to scale up by running the processes in different threads.</p><p>I’m so lucky Spring Batch permits it; let’s see the documentation:</p><blockquote>Multi-threaded Step</blockquote><blockquote>The simplest way to start parallel processing is to add a TaskExecutor to your Step configuration.</blockquote><p>But what the documentation does not tell you is that it works perfectly if, in the processor, you don’t have any database access.</p><p>In my case, to generate the billing lines, I need to access some data from the database, and doing this with the solution proposed in the official documentation causes some problems like the following:</p><pre>2025-05-02 20:45:26,367 localhost- process[22329] - [main] [] ERROR - o.s.batch.core.step.AbstractStep - Encountered an error executing step onlineBillRecorderStep in job myJob<br>org.springframework.batch.core.step.FatalStepExecutionException: JobRepository failure forcing rollback<br> at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:442)<br> at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:307)<br> at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140)<br> at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:250)<br> at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:82)<br> at org.springframework.batch.repeat.support.TaskExecutorRepeatTemplate$ExecutingRunnable.run(TaskExecutorRepeatTemplate.java:261)<br> at java.base/java.lang.Thread.run(Thread.java:1447)<br>Caused by: org.springframework.jdbc.UncategorizedSQLException: PreparedStatementCallback; uncategorized SQLException for SQL [UPDATE BATCH_STEP_EXECUTION_CONTEXT<br>SET SHORT_CONTEXT = ?, SERIALIZED_CONTEXT = ?<br>WHERE STEP_EXECUTION_ID = ?<br>]; SQL state [HY000]; error code [1020]; (conn=143) Record has changed since last read in table &#39;BATCH_STEP_EXECUTION_CONTEXT&#39;<br> at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1557)<br> at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:677)<br> at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:972)<br> at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:1016)<br> at org.springframework.batch.core.repository.dao.JdbcExecutionContextDao.persistSerializedContext(JdbcExecutionContextDao.java:306)<br> at org.springframework.batch.core.repository.dao.JdbcExecutionContextDao.updateExecutionContext(JdbcExecutionContextDao.java:207)<br> at org.springframework.batch.core.repository.support.SimpleJobRepository.updateExecutionContext(SimpleJobRepository.java:244)<br> at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)<br> at java.base/java.lang.reflect.Method.invoke(Method.java:565)<br> at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:359)<br> at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:196)<br> at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)<br> at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:380)<br> at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)<br> at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)<br> at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:223)<br> at jdk.proxy2/jdk.proxy2.$Proxy231.updateExecutionContext(Unknown Source)<br> at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:429)<br> ... 6 common frames omitted<br>Caused by: java.sql.SQLException: (conn=143) Record has changed since last read in table &#39;BATCH_STEP_EXECUTION_CONTEXT&#39;<br> at org.mariadb.jdbc.export.ExceptionFactory.createException(ExceptionFactory.java:306)<br> at org.mariadb.jdbc.export.ExceptionFactory.create(ExceptionFactory.java:378)<br> at org.mariadb.jdbc.message.ClientMessage.readPacket(ClientMessage.java:189)<br> at org.mariadb.jdbc.client.impl.StandardClient.readPacket(StandardClient.java:1235)<br> at org.mariadb.jdbc.client.impl.StandardClient.readResults(StandardClient.java:1174)<br> at org.mariadb.jdbc.client.impl.StandardClient.readResponse(StandardClient.java:1093)<br> at org.mariadb.jdbc.client.impl.StandardClient.execute(StandardClient.java:1017)<br> at org.mariadb.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:101)<br> at org.mariadb.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:314)<br> at org.mariadb.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:291)<br> at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)<br> at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)<br> at org.springframework.jdbc.core.JdbcTemplate.lambda$update$2(JdbcTemplate.java:977)<br> at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:658)<br> ... 22 common frames omitted<br></pre><p>So concretely, what happens here? When accessing the database, the <em>EntityManager</em> manages a transaction and commits it, so the versions of the step are different, and the <em>Exception</em> occurs.</p><h4>How to fix it?</h4><p>The solution seems a bit obvious; you need a new transaction for the <em>ItemProcessor</em>.</p><p>I searched for a moment, but even if the <em>ItemProcessor</em> is not annotated with <em>@Component,</em> you just have to add the <em>@Transactional</em> annotation on the process method, something like this:</p><pre>public class MyItemProcessor implements ItemProcessor&lt;InObject, OutObject&gt; {<br>  @Override<br>  @Transactional(propration = Propagation.REQUIRES_NEW)<br>  public OutObject process(InObject obj) {<br>    return new OutObject();<br>  }</pre><p>By doing this, you indicate to Spring that the process method needs a new transaction, and by doing this, you let the transaction of the step continue without affecting it.</p><p>That’s all for today! Enjoy your day, and always try to make the most efficient code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=664cb7c6ea1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>