<?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 Dinakaran Ramadurai on Medium]]></title>
        <description><![CDATA[Stories by Dinakaran Ramadurai on Medium]]></description>
        <link>https://medium.com/@dinakaranramadurai?source=rss-636f16551111------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zzMnFJyE3aCRTBYX3pnW7w.jpeg</url>
            <title>Stories by Dinakaran Ramadurai on Medium</title>
            <link>https://medium.com/@dinakaranramadurai?source=rss-636f16551111------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:33:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dinakaranramadurai/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[Reducing RDS CPU Utilization by Explain Analyze]]></title>
            <link>https://dinakaranramadurai.medium.com/reducing-rds-cpu-utilization-by-explain-analyze-231f93b50bc8?source=rss-636f16551111------2</link>
            <guid isPermaLink="false">https://medium.com/p/231f93b50bc8</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[rds-postgres]]></category>
            <category><![CDATA[performance-insights]]></category>
            <category><![CDATA[aws-rds]]></category>
            <category><![CDATA[sql-optimization]]></category>
            <dc:creator><![CDATA[Dinakaran Ramadurai]]></dc:creator>
            <pubDate>Sun, 14 Jul 2024 14:02:35 GMT</pubDate>
            <atom:updated>2024-07-14T14:02:35.121Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Amazon RDS with postgresql logo" src="https://cdn-images-1.medium.com/max/1024/0*WlgRz7QNpC9qHfEE.jpg" /></figure><h3>Problem Statement</h3><p>Consider we were running an application that takes the data from queues and process it. Initially we had a very less load so we didn&#39;t see any spike in RDS. After some days we increased the load from say100 messages/second to 10000 message/second. From the moment we increased the load we can see spike in RDS CPU Utilization. Also the performance of the application started degrading. It also started to take more than 2 minutes to process one message. Once we noticed this we have decreased the load to pause this spike temporarily</p><h3>How to Identify RDS CPU Utilization</h3><p>Increases in CPU utilization can be caused by several factors, such as user-initiated heavy workloads, multiple concurrent queries, or long-running transactions.</p><p>To identify the source of the CPU usage in your Amazon RDS for PostgreSQL instance, review the following approaches:</p><ul><li>Enhanced Monitoring</li><li>Performance Insights</li><li>Queries that detect the cause of CPU utilization in the workload</li><li>Logs with activated monitoring</li></ul><p>After you identify the source, you can analyze and optimize your workload to reduce CPU usage.</p><h3>Enhanced Monitoring</h3><p>In AWS console, go to RDS, Choose the database, Monitoring Tab and choose Enhanced Monitoring in cloud watch</p><figure><img alt="CPU Utilization image of AWS cloud watch — Enhanced monitoring" src="https://cdn-images-1.medium.com/max/1024/0*eL_k4xagFen79vPG.png" /></figure><p>Find the Timeframe where you see CPU Utilization high. In the above example we can see the CPU Utilization goes near to 100% at 2/3 16:00</p><h3>Performance Insights</h3><p>In AWS console, go to RDS, Performance Insights and choose the required database. you will see one same as below</p><figure><img alt="Performance Insigts of AWS RDS" src="https://cdn-images-1.medium.com/max/1024/0*f-mKQ6LV5reSyfjP.png" /></figure><p>From this, choose the timeframe we have noticed in Enhanced Monitoring. Here we can see get the Top SQL that is low performing and also the CPU utilization of corresponding SQL in green color. Now we have to find why the query is taking more time to execute. Lets find the reason for it. It can be done by using explain and analyze of PostgreSQL. Lets see how we can find it.</p><h3>Explain &amp; Analyze</h3><p>Consider a table Tweet contains one to many relationship with comment table. Number of tweets is 107042 and number of comments is 1768226.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*RwMMKzdCvFGuCGtNaX5PpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*Y-6Bxs3GJ1fbGane0rXzfA.png" /></figure><p>Query that is causing CPU Utilization high is below</p><pre>select t.id, t.tweet, c.id, c.&quot;comment&quot;, c.tweet_id from tweet t join &quot;comments&quot; c on t.id = c.tweet_id<br>where t.id = $1;</pre><p>If you notice this query everything looks perfect. we are trying to retrieve only one tweet with all its comments. how can it go wrong? lets understand this with explain and analyze</p><p>Run the below query in PG Admin or PostgreSQL.</p><pre>explain analyze select t.id, t.tweet, c.id, c.&quot;comment&quot;, c.tweet_id from tweet t join &quot;comments&quot; c on t.id = c.tweet_id<br>where t.id = 13;</pre><p>If needed for u to play around. Attached the SQL backup <a href="https://github.com/dinakaranram9/queryplan/blob/master/queryplan_without_index.sql">here</a>. Please find below the response of above query with explain analyze.</p><figure><img alt="explain analyze of query without index creation" src="https://cdn-images-1.medium.com/max/727/1*2RIeWplAB8vkqyhGjsgfkQ.png" /></figure><figure><img alt="Graph of explain analyze without index creation" src="https://cdn-images-1.medium.com/max/1024/1*mikrZRxjC-Jw1be7vOtuaw.png" /></figure><p>If you see the query plan, you can see when we join comments table and tweet table, while fetching comments based on tweet id, it is performing sequential scan on comments table which is causing the cost of 1000. so the culprit is sequential scan on tweet_id column.</p><h3>Solution</h3><p>Now the solution is index creation on tweet_id. Lets create an index tweet_id and see how explain and analyze changes.</p><pre>CREATE INDEX IF NOT EXISTS TWEET_ID_IDX ON comments(tweet_id)</pre><blockquote>Note — If you are going to create index on already production live database, please note that index creation will try to lock the row for creating index. If the row is being locked by application then it will skipped and index creation may take several hours to complete until it create index for all rows.</blockquote><p>After Index creation, we can able to see sequential scan of tweet_id on comments table got changed to index scan which reduced the cost from 1000 to 0.4.</p><figure><img alt="explain analyze of query with index creation" src="https://cdn-images-1.medium.com/max/723/1*iL9KsAUWHOok894YMn3psQ.png" /></figure><figure><img alt="graph of explain analyze with index creation" src="https://cdn-images-1.medium.com/max/1024/1*ruyG4EHAI3DopFG9G09Ynw.png" /></figure><h3>Conclusion</h3><p>After this index creation we again increased the load of the application and there is no spike in CPU Utilization of RDS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=231f93b50bc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chat GPT — Bill amount extraction using chat GPT web API and python]]></title>
            <link>https://dinakaranramadurai.medium.com/chat-gpt-bill-amount-extraction-using-chat-gpt-web-api-and-python-68bae629af2?source=rss-636f16551111------2</link>
            <guid isPermaLink="false">https://medium.com/p/68bae629af2</guid>
            <category><![CDATA[chatgptapi]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[openai-api]]></category>
            <category><![CDATA[bill-amount-extraction]]></category>
            <category><![CDATA[python-chatgpt]]></category>
            <dc:creator><![CDATA[Dinakaran Ramadurai]]></dc:creator>
            <pubDate>Sat, 29 Apr 2023 08:02:33 GMT</pubDate>
            <atom:updated>2023-04-29T08:02:33.665Z</atom:updated>
            <content:encoded><![CDATA[<h3>Chat GPT — Bill amount extraction using chat GPT web API and python</h3><figure><img alt="Learn Everything About The OpenAI Python Library &amp; 5 Remarkable… – Towards  AI" src="https://cdn-images-1.medium.com/proxy/1*EOoGf6vYe0dkZhunIyEwZg.png" /><figcaption>Open AI API with Python</figcaption></figure><h3>Problem Statement</h3><p>In many organizations, they have a portal where we can reimburse the amount we spend on business travel, stay, etc., In most organizations, there will be a person who approves the amount by manually going through the bill and the submitter also have to type the amount by uploading each bill. This might go wrong many times and it will be hectic if there are bills for a month. we are trying to solve this problem using chat GPT web API and python</p><h3>Generating Open API keys</h3><p>Create an account in open API by navigating to this <a href="https://platform.openai.com/">link</a>. Once you created the account navigate to Account -&gt; View API keys, and click on Create a new secret. Give a secret name and click on Create secret key. Now the secret key will be created. you can also navigate to API keys through this <a href="https://platform.openai.com/account/api-keys">link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZS3z3qrdCQW4t0xnccEP0A.png" /><figcaption>Secret name : Dinakaran</figcaption></figure><h3>Python Implementation</h3><h4>Prerequisites</h4><ul><li>The OpenAI library. You can install it using pip: pip install openai</li><li>To read pdf and extract text. You have to install Fitz : pip install fitz</li><li>To read images and extract text. you have to install py-tesseract : pip install pytesseract</li><li>Additionally, to read the images we have to additionally install Tesseract-ocr from this <a href="https://github.com/UB-Mannheim/tesseract/wiki">link</a>.</li></ul><h4>Setting up the code</h4><p>First, let’s import the necessary libraries and set up the API key.</p><pre>import fitz, openai, datetime, pytesseract<br>pytesseract.pytesseract.tesseract_cmd = r&#39;C:\\Program Files\\Tesseract-OCR\\tesseract&#39;  <br>from PIL import Image</pre><p>Next step, extract the text from the pdf/image so that we can prompt to chat GPT API and get the result.</p><pre># Open the PDF file<br>pdf_file = &#39;C:\\Dinakaran\\Test\\Test.pdf&#39;<br>pdf_doc = fitz.open(pdf_file)<br><br># Extract text from each page<br>pdf_text = &#39;&#39;<br>for page in pdf_doc:<br>    pdf_text += page.get_text()<br><br># Close the PDF file<br>pdf_doc.close()</pre><p>For images use this to extract text from images</p><pre># Open the image<br>image = Image.open(&quot;C:\\Dinakaran\\Test\\Test.jpg&quot;)<br><br># Convert the image to grayscale<br>image = image.convert(&quot;L&quot;)<br><br># Perform OCR using Tesseract<br>image_text = pytesseract.image_to_string(image)</pre><p>Now we can start requesting open API with the prompt to get the completion</p><pre>prompt = f&#39;&#39;&#39;Assuming yourself as a financial evaluator and extract the total bill amount from the bill  {image_text}. Also tell the accuracy of the result retrieved with tax details&#39;&#39;&#39;<br><br>print(&quot;Contacting OpenAI&quot;)<br>completions = openai.Completion.create(<br>    engine=&quot;text-davinci-003&quot;,<br>    prompt=prompt,<br>    max_tokens=2048,<br>    n=1,<br>    stop=None,<br>    temperature=0.3,<br>)<br><br>message = completions.choices[0].text<br>print(message)</pre><ul><li>prompt: The prompt or context for the conversation. This can be a single line of text or a multi-line prompt separated by newlines.</li><li>model_engine: The name of the model you want to use. We will be using the text-davinci-003 model for this tutorial. To learn more about the model go to the link <a href="https://platform.openai.com/docs/models">here</a>.</li><li>max_tokens: The maximum number of tokens (words and punctuation) to generate in the response. The minimum is 1 and the maximum is 2048.</li><li>temperature: Accepted value between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.</li><li>n: How many completions should be used to generate for each prompt.</li><li>stop:Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence.</li></ul><p><strong>Response</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*4rGkDLBS-Apfwq9sIYqiPg.png" /><figcaption>Response from Open API</figcaption></figure><p><strong>Conclusion</strong></p><p>There are many tools in the market that can do the same. But one thing that stands out about chat GPT from my perspective it can be trained to do 100 different things that 100 tools can do it. so we can replace 1 tool with 100 tools licensing that will help us save money.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68bae629af2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migration from Swagger to open-api with Spring boot 3]]></title>
            <link>https://dinakaranramadurai.medium.com/migration-from-swagger-to-open-api-with-spring-boot-3-4a172db66e32?source=rss-636f16551111------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a172db66e32</guid>
            <category><![CDATA[swagger-to-open-api]]></category>
            <category><![CDATA[migration-from-swagger]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[spring-boot-3]]></category>
            <dc:creator><![CDATA[Dinakaran Ramadurai]]></dc:creator>
            <pubDate>Sat, 11 Feb 2023 06:24:23 GMT</pubDate>
            <atom:updated>2023-02-11T06:24:23.161Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are using Swagger-UI, it is time to switch to Spring Doc as swagger is a dead project. Swagger hasn’t had a release since <a href="https://github.com/springfox/springfox/releases/tag/3.0.0">July 2020</a>. Even though it worked with spring boot 2.x, it won&#39;t work well for spring boot 3 as it has many breaking changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*bifx98osmioynY3QWx-A-g.png" /><figcaption>Migrating from swagger to open-api</figcaption></figure><h3><strong>What is SpringDoc-OpenAPI?</strong></h3><p>springdoc-openapi java library helps to automate the generation of API documentation using spring boot projects. Automatically generates documentation in JSON/YAML and HTML format APIs. This documentation can be completed by comments using swagger-api annotations.</p><h3>Dependencies</h3><p>Remove spring fox and swagger 2 dependencies. Add springdoc-openapi-ui dependency based on application type web MVC or web flux</p><pre>&lt;!-- provides springdoc-openapi-ui --&gt;<br>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springdoc&lt;/groupId&gt;<br>   &lt;artifactId&gt;springdoc-openapi-starter-webmvc-ui&lt;/artifactId&gt;<br>   &lt;version&gt;2.0.2&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springdoc&lt;/groupId&gt;<br>   &lt;artifactId&gt;springdoc-openapi-starter-webmvc-api&lt;/artifactId&gt;<br>   &lt;version&gt;2.0.2&lt;/version&gt;<br> &lt;/dependency&gt;</pre><p>Replace swagger 2 annotations with swagger 3 annotations (it is already included with springdoc-openapi-ui dependency). Package for swagger 3 annotations is io.swagger.v3.oas.annotations.</p><pre>@Api → @Tag<br>@ApiIgnore → @Parameter(hidden = true) or @Operation(hidden = true) or @Hidden<br>@ApiOperation(value = &quot;foo&quot;, notes = &quot;bar&quot;) → @Operation(summary = &quot;foo&quot;, description = &quot;bar&quot;)<br>@ApiParam → @Parameter</pre><h3>Configurations</h3><p><strong>API Info details — </strong>In swagger</p><pre>//API info<br>private ApiInfo apiInfo() {<br>  return new ApiInfo(&quot;Micro service&quot;, &quot;APIs for Test Console service&quot;, &quot;1.0&quot;,<br>    &quot;Terms of service&quot;,<br>    new Contact(&quot;Dev Team&quot;, &quot;https://github.com&quot;, &quot;dinakar14.ram@gmail.com&quot;), &quot;License of API&quot;,<br>    &quot;API license URL&quot;, Collections.emptyList());<br> }</pre><p>In Spring Doc open-api</p><pre>@Bean<br> public OpenAPI springOpenAPI() {<br>  return new OpenAPI()<br>    .info(new Info().title(&quot;Micro service&quot;).description(&quot;APIs for Test Console service&quot;).version(&quot;1.0&quot;)<br>      .license(new License().name(&quot;Dev Team&quot;).url(https://medium.com/&quot;https://github.com&quot;)))<br>    .externalDocs(new ExternalDocumentation().description(&quot;Test Documentation&quot;).url(https://medium.com/&quot;https://github.com&quot;));<br> }</pre><p>If you have <strong>multiple</strong> Docket beans replace them with GroupedOpenApi beans. In Swagger</p><pre>@Bean<br>  public Docket publicApi() {<br>      return new Docket(DocumentationType.SWAGGER_2)<br>              .select()<br>              .apis(RequestHandlerSelectors.basePackage(&quot;com.dina.openapi.controller&quot;))<br>              .paths(PathSelectors.ant(&quot;/api/**&quot;))<br>              .build()<br>              .groupName(&quot;test-api&quot;)<br>              .apiInfo(apiInfo());<br>  }</pre><p>In Spring Doc open-api</p><pre>@Bean<br> public GroupedOpenApi publicApi() {<br>  return GroupedOpenApi.builder().group(&quot;test-api&quot;).pathsToMatch(&quot;/api/**&quot;).build();<br> }</pre><p>If you have only one docket, you can add the below in the application.properties</p><pre>springdoc.packagesToScan=com.dina.openapi.controller<br>springdoc.pathsToMatch=/api/**</pre><h3>Authorization</h3><p>In Swagger</p><pre>@Bean<br> public Docket api() {<br><br>  return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())<br>    .securityContexts(Arrays.asList(securityContext())).securitySchemes(Arrays.asList(apiKey())).select()<br>    .apis(RequestHandlerSelectors.basePackage(&quot;com.dina.openapi.controller&quot;))<br>    .paths(PathSelectors.ant(&quot;/api/**&quot;)).build();<br> }<br><br>private ApiKey apiKey() {<br>  return new ApiKey(&quot;apiKey&quot;, &quot;Authorization&quot;, &quot;header&quot;);<br> }<br><br> private SecurityContext securityContext() {<br>  return SecurityContext.builder().securityReferences(defaultAuth()).build();<br> }<br><br> private List&lt;SecurityReference&gt; defaultAuth() {<br>  return Arrays.asList(new SecurityReference(&quot;apiKey&quot;, new AuthorizationScope[0]));<br> }</pre><p>In spring Doc open api</p><pre>@Bean<br> public OpenAPI customizeOpenAPI() {<br>  final String securitySchemeName = &quot;bearerAuth&quot;;<br>  return new OpenAPI()<br>    .addSecurityItem(new SecurityRequirement().addList(securitySchemeName))<br>          .components(<br>              new Components()<br>                  .addSecuritySchemes(securitySchemeName,<br>                      new SecurityScheme()<br>                          .name(securitySchemeName)<br>                          .type(SecurityScheme.Type.HTTP)<br>                          .scheme(&quot;bearer&quot;)<br>                          .bearerFormat(&quot;JWT&quot;)<br>                  )<br>          );<br> }</pre><h3>Global Headers</h3><p>In swagger</p><pre>@Bean<br> public Docket api() {<br>  return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())<br>    .securityContexts(Arrays.asList(securityContext())).securitySchemes(Arrays.asList(apiKey())).select()<br>    .apis(RequestHandlerSelectors.basePackage(&quot;com.dina.openapi.controller&quot;))<br>    .paths(PathSelectors.ant(&quot;/api/**&quot;)).build()<br>    .globalRequestParameters(Arrays.asList(new RequestParameterBuilder().name(&quot;test-header&quot;)<br>      .description(&quot;Test Header&quot;).in(ParameterType.HEADER).required(true)<br>      .query(simpleParameterSpecificationBuilder -&gt; simpleParameterSpecificationBuilder<br>        .allowEmptyValue(false).model(modelSpecificationBuilder -&gt; modelSpecificationBuilder<br>          .scalarModel(ScalarType.STRING)))<br>      .build()));<br> }</pre><p>In Spring Doc open-api, you have to handle the duplicate in parameter list so that headers doesn’t appear twice. This issue happens since open-api scans the controller class, adds the request header into parameter list and shows them in /swagger-ui.html. when you add the same header as global header, since it is a list it would appear twice. It is handled automatically in swagger but in open-api we have to handle it.</p><pre>public static final String TEST_HEADER = &quot;test-header&quot;;<br> <br> @Bean<br> public GroupedOpenApi publicApi() {<br>  return GroupedOpenApi.builder().group(&quot;test-api&quot;).pathsToMatch(&quot;/api/**&quot;).build();<br> }<br> <br> @Bean<br> public OperationCustomizer customGlobalHeaders() {<br><br>  return (Operation operation, HandlerMethod handlerMethod) -&gt; {<br>   Optional&lt;List&lt;Parameter&gt;&gt; isParameterPresent = Optional.ofNullable(operation.getParameters());<br>   Boolean isTestHeaderPresent = Boolean.FALSE;<br>   if (isParameterPresent.isPresent()) {<br>    isTestHeaderPresent = isParameterPresent.get().stream()<br>      .anyMatch(param -&gt; param.getName().equalsIgnoreCase(TEST_HEADER));<br>   }<br>   if (Boolean.FALSE.equals(isTestHeaderPresent)) {<br>    Parameter remoteUser = new Parameter().in(ParameterIn.HEADER.toString()).schema(new StringSchema())<br>      .name(TEST_HEADER).description(&quot;Test Header&quot;).required(true);<br>    operation.addParametersItem(remoteUser);<br>   }<br>   return operation;<br>  };<br> }</pre><h3>Deploying behind Proxy like Spring cloud gateway</h3><p>If you deploy your micro service that has Spring Doc open-api behind reverse proxy like spring cloud gateway, you have to add the following in application.properties</p><pre>server.forward-headers-strategy=framework</pre><p>This is because you request might change along the way. Your application may be running on 11.11.11.11:8080, but HTTP clients should only see github.org. Forward Headersdefines the Forwarded HTTP header; proxies can use this header to provide information about the original request</p><h3><strong>Conclusion</strong></h3><p>To access the spring doc open-api UI type the following in browser— <a href="http://localhost:8080/swagger-ui/index.html">http://localhost:8080/swagger-ui/index.html</a></p><p>If you are still using swagger, it is going to die migrate to Spring Doc open-api.</p><p>As always. you can check the code here at — <a href="https://github.com/dinakaranram9/open-api.git">https://github.com/dinakaranram9/open-api.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a172db66e32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pitfalls of Lombok — Efficient way to use EqualsAndHashCode in the entity class]]></title>
            <link>https://dinakaranramadurai.medium.com/pitfalls-of-lombok-efficient-way-to-use-equalsandhashcode-in-the-entity-class-d06d8b9dbc0b?source=rss-636f16551111------2</link>
            <guid isPermaLink="false">https://medium.com/p/d06d8b9dbc0b</guid>
            <category><![CDATA[hashcode-java]]></category>
            <category><![CDATA[equals]]></category>
            <category><![CDATA[lombok]]></category>
            <category><![CDATA[equals-java]]></category>
            <category><![CDATA[equals-and-hashcode-java]]></category>
            <dc:creator><![CDATA[Dinakaran Ramadurai]]></dc:creator>
            <pubDate>Sat, 14 Jan 2023 09:13:33 GMT</pubDate>
            <atom:updated>2023-01-14T09:13:33.516Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pitfalls of Lombok — Efficient way to use EqualsAndHashCode in the entity class</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NNaJiXuXiDDzQyBr9yNjfQ.png" /><figcaption>Pitfalls of Lombok — Efficient way to use @EqualsAndHashCode in the entity class</figcaption></figure><p>It is a typical day in a developer’s life to copy and paste from the internet. Consider two entity classes — Tweet and Comment with a one-to-many relationship between Tweet and Comment. Most of the developers will annotate their entity class with @EqualsAndHashCode of Lombok without knowing the actual need for it. In entity class, the hashcode() method should always return the fixed value of something like 100, and the equals() method should compare only the type of object, primary key equality with the null check as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e768f86122d020d886829843638f824f/href">https://medium.com/media/e768f86122d020d886829843638f824f/href</a></iframe><p>If you don&#39;t want to implement it you can annotate with @EqualsAndHashCode of Lombok like below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5941cb1e4924e5bd770d125439fb61f2/href">https://medium.com/media/5941cb1e4924e5bd770d125439fb61f2/href</a></iframe><p>So Lombok will generate equals() and hashcode() methods for us as shown below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b49a7696919c3edca700ba7d056771c/href">https://medium.com/media/1b49a7696919c3edca700ba7d056771c/href</a></iframe><p>If you closely observe these two methods we can able to find multiple issues. The first one is Lombok including all the non-final methods in equals() and hashcode() calculation which is not required. we know that in entity class two objects will be equal if their primary key is equal. This will increase the overhead of equals() and hashcode() methods.</p><p>You can change that by setting the <strong><em>onlyExplicitlyIncluded </em></strong>attribute of the <em>@EqualsAndHashCode</em> annotation to <em>true</em> and annotating the primary key attribute with <strong><em>@EqualsAndHashCode.Include </em></strong><em>as shown below</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52f7c9841c9ad526546160f2e4daf283/href">https://medium.com/media/52f7c9841c9ad526546160f2e4daf283/href</a></iframe><p>Now Lombok will generate equals() and hashcode() methods with the id field alone as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fe002a77c6f0bc65c0286b76f6f10da/href">https://medium.com/media/9fe002a77c6f0bc65c0286b76f6f10da/href</a></iframe><p>Now you might think this might solved the issue, but it&#39;s not. This equals() method will return true if the primary key of both objects is null which shouldn’t happen. The equals() method should always return false for two objects with null as the primary key. Because of this issue, you cannot add two new entity objects to the set</p><p><strong>Conclusion</strong></p><p>.That implies you cannot add two new Comments to the Tweet entity. Thus you should avoid using the @EqualsAndHashCode of Lombok.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d06d8b9dbc0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bulk/Batch insert using Spring Data JPA and Mysql database]]></title>
            <link>https://dinakaranramadurai.medium.com/bulk-batch-insert-using-spring-data-jpa-and-mysql-database-464d89bb243e?source=rss-636f16551111------2</link>
            <guid isPermaLink="false">https://medium.com/p/464d89bb243e</guid>
            <category><![CDATA[batch-insert-with-mysql]]></category>
            <category><![CDATA[bulk-insert-with-mysql]]></category>
            <category><![CDATA[batch-insert-with-jpa]]></category>
            <category><![CDATA[bulk-insert-with-jpa]]></category>
            <category><![CDATA[mysql-and-jpa]]></category>
            <dc:creator><![CDATA[Dinakaran Ramadurai]]></dc:creator>
            <pubDate>Sat, 01 Oct 2022 10:39:51 GMT</pubDate>
            <atom:updated>2022-10-01T10:39:51.468Z</atom:updated>
            <content:encoded><![CDATA[<p>Is batch insert not working as expected as you are using the Mysql database with Spring Data JPA?</p><p>Adding these dependencies also hasn’t helped ?</p><blockquote>spring.jpa.properties.hibernate.jdbc.batch_size:5000</blockquote><blockquote>spring.jpa.properties.hibernate.order_inserts:true</blockquote><blockquote>spring.jpa.properties.hibernate.order_updates: true</blockquote><p>Don&#39;t worry you are in the right place. Let&#39;s explore together the ways to solve it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8ymRwew-bj-xlSx_4v7yA.jpeg" /></figure><p>As I always say if you are using spring data JPA and haven’t added these lines in your application.properties while developing you won’t come across this issue, your application performance will go down</p><blockquote><strong><em>spring.jpa.show-sql: true</em></strong></blockquote><h3>Reasons for MySQL not allowing batch insert with JPA</h3><p><strong><em>Using Sequence Generators to auto-generate id column</em></strong> — Neither MySQL 5.7 nor 8.0 support SEQUENCE objects. Consider a below entity class with service class</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/424d3b7a06b4f9a1e1705984d9c6682a/href">https://medium.com/media/424d3b7a06b4f9a1e1705984d9c6682a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c2f4c4c45d271af29a562691e2a6b1c/href">https://medium.com/media/5c2f4c4c45d271af29a562691e2a6b1c/href</a></iframe><p>If you try to use sequence and insert 5 records using JPA, you will see 11 queries executed to insert 5 records, so we should not consider using sequence with Mysql</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2rRDf2v-uPvQT3M-esQu8A.png" /><figcaption>Logs while using sequence</figcaption></figure><p>The best way to auto-generate column id is below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0454fd912aaed145f6973d8b9dc7163d/href">https://medium.com/media/0454fd912aaed145f6973d8b9dc7163d/href</a></iframe><p>Let&#39;s re-run the insertion of 5 records again. you will see 5 queries executed to insert 5 records not bad than sequence. It happens since the IDENTITY generator disables JDBC batch inserts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*3_DIEb3nXyEtF6DM6HKENw.png" /><figcaption>Log while using identity generator</figcaption></figure><h3>Conclusion</h3><p>Here it comes. JPA with MySQL won&#39;t support batching. we have to either use JDBC Template or query DSL-SQL or jooq.</p><p>To implement query DSL-SQL, click <a href="https://dinakaranramadurai.medium.com/bulk-batch-insert-using-query-dsl-sql-f43abee753bc">here</a>.</p><p>To implement JDBC Template, click <a href="https://dinakaranramadurai.medium.com/bulk-batch-insert-using-jdbc-template-bf7d02d42556">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=464d89bb243e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bulk/Batch insert using query DSL-SQL]]></title>
            <link>https://dinakaranramadurai.medium.com/bulk-batch-insert-using-query-dsl-sql-f43abee753bc?source=rss-636f16551111------2</link>
            <guid isPermaLink="false">https://medium.com/p/f43abee753bc</guid>
            <category><![CDATA[batch-using-querydsl]]></category>
            <category><![CDATA[bulk-insert-with-querydsl]]></category>
            <category><![CDATA[bulk-insert]]></category>
            <category><![CDATA[querydsl-sql]]></category>
            <category><![CDATA[querydsl]]></category>
            <dc:creator><![CDATA[Dinakaran Ramadurai]]></dc:creator>
            <pubDate>Sat, 01 Oct 2022 10:31:00 GMT</pubDate>
            <atom:updated>2022-10-01T10:40:22.068Z</atom:updated>
            <content:encoded><![CDATA[<p>According to my previous blog — <a href="https://dinakaranramadurai.medium.com/bulk-batch-insert-using-spring-data-jpa-and-mysql-database-464d89bb243e">Bulk/Batch insert using Spring Data JPA and Mysql database</a>, we can understand that batch insert is not possible with JPA using Mysql as database. we have to either go with JdbcTemplate or query DSL-SQL</p><p>In this blog, let&#39;s try to implement query DSL-SQL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8ymRwew-bj-xlSx_4v7yA.jpeg" /><figcaption>cover pic</figcaption></figure><h3>Maven dependencies to be added</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d3dde48f51a1a9a39cf2962678b93f3/href">https://medium.com/media/3d3dde48f51a1a9a39cf2962678b93f3/href</a></iframe><h3>Code generation</h3><p>we have to generate the class files that act as an abstraction of our database schema. There are two ways to generate code: The maven plugin or through code configurations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/294ea3c0cc041ac57d1f2a78a2c2b5f5/href">https://medium.com/media/294ea3c0cc041ac57d1f2a78a2c2b5f5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2159c0d97069119824487a9e2709559d/href">https://medium.com/media/2159c0d97069119824487a9e2709559d/href</a></iframe><p>Let’s create an entity class tweets where we can store tweets</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0454fd912aaed145f6973d8b9dc7163d/href">https://medium.com/media/0454fd912aaed145f6973d8b9dc7163d/href</a></iframe><p>If you are using the <strong>maven plugin</strong> -&gt; run <strong>mvn clean install. </strong>For<strong><br>code, start the server. </strong>Now you can see the <strong>Qclass </strong>files were generated above the database schema you have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*q3BW4JHqjbMaW7vD-W1K3A.png" /><figcaption>the generated class file above the schema</figcaption></figure><p>Now let&#39;s get into the war zone. Let&#39;s create a service class that inserts a batch of records into the tweet table using query DSL-SQL. To do that follow the simple code below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49bc350b9e1e6eefc918a1efd0976968/href">https://medium.com/media/49bc350b9e1e6eefc918a1efd0976968/href</a></iframe><p>Now if you run the above method, you will notice that the entire data gets inserted into the database using a single query as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3cVmxPYk6xm60mmjY2H4zQ.png" /><figcaption>log while running batch through query DSL-SQL</figcaption></figure><p>To see the below log you have to add the maven dependency — <strong>datasource-proxy-spring-boot-starter</strong> with properties — <strong>logging.level.net.ttddyy.dsproxy.listener=debug. </strong>This helps you to see the queries that are actually performed on our database.</p><p><strong>Advantages of using query DSL-SQL</strong></p><ol><li>Type-safe code</li><li>Dynamic queries</li><li>Lesser time for code to reach production</li></ol><p><strong>Conclusion</strong></p><p>we can able to batch insert the records using query DSL-SQL maven dependency on MySQL database. this is cool, right?</p><p>For GitHub code click <a href="https://github.com/dinakaranram9/query-DSL-SQL">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f43abee753bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bulk/Batch insert using JDBC template]]></title>
            <link>https://dinakaranramadurai.medium.com/bulk-batch-insert-using-jdbc-template-bf7d02d42556?source=rss-636f16551111------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf7d02d42556</guid>
            <category><![CDATA[bulk-insert-using-jdbc]]></category>
            <category><![CDATA[jdbc-tempalte]]></category>
            <category><![CDATA[batch-insert-using-jdbc]]></category>
            <category><![CDATA[bulk-insert-using-spring]]></category>
            <category><![CDATA[bulk-insert]]></category>
            <dc:creator><![CDATA[Dinakaran Ramadurai]]></dc:creator>
            <pubDate>Sat, 01 Oct 2022 10:29:26 GMT</pubDate>
            <atom:updated>2022-10-01T10:40:41.598Z</atom:updated>
            <content:encoded><![CDATA[<p>According to my previous blog — <a href="https://dinakaranramadurai.medium.com/bulk-batch-insert-using-spring-data-jpa-and-mysql-database-464d89bb243e">Bulk/Batch insert using Spring Data JPA and Mysql database</a>, we can understand that batch insert is not possible with JPA using Mysql as database. we have to either go with JdbcTemplate or query DSL-SQL.</p><p>In this blog, let’s try to implement the JDBC template</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8ymRwew-bj-xlSx_4v7yA.jpeg" /><figcaption>cover picture</figcaption></figure><p>Maven Dependencies to be added</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae76a6800b086e4929f31eb9b63c04fc/href">https://medium.com/media/ae76a6800b086e4929f31eb9b63c04fc/href</a></iframe><p>Let’s create an entity class tweets where we can store tweets</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0454fd912aaed145f6973d8b9dc7163d/href">https://medium.com/media/0454fd912aaed145f6973d8b9dc7163d/href</a></iframe><p>Let’s create a service class that inserts a batch of records into the tweet table using the JDBC Template. To do that follow the simple code below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d0f975932408bae81c629fcf042919e/href">https://medium.com/media/2d0f975932408bae81c629fcf042919e/href</a></iframe><p>Now if you run the above method, you will notice that the entire data gets inserted into the database using a single query as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3cVmxPYk6xm60mmjY2H4zQ.png" /><figcaption>log while running batch through query DSL-SQL</figcaption></figure><p>To see the below log you have to add the maven dependency — <strong>datasource-proxy-spring-boot-starter</strong> with properties — <strong>logging.level.net.ttddyy.dsproxy.listener=debug. </strong>This helps you to see the queries that are actually performed on our database.</p><p><strong>Advantages of using JDBC Template</strong></p><p>Jdbc will be faster than query-DSL SQL and Spring Data JPA</p><p><strong>Conclusion</strong></p><p>we can able to batch insert the records using the JDBC template on the MySQL database. this is cool, right?</p><p>For GitHub code click <a href="https://github.com/dinakaranram9/query-DSL-SQL">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf7d02d42556" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring JPA generating many queries : n+1 query problem]]></title>
            <link>https://dinakaranramadurai.medium.com/spring-jpa-generating-many-queries-n-1-query-problem-a54a5da5bca3?source=rss-636f16551111------2</link>
            <guid isPermaLink="false">https://medium.com/p/a54a5da5bca3</guid>
            <category><![CDATA[jpa-optimization]]></category>
            <category><![CDATA[jpa-issues]]></category>
            <category><![CDATA[n-plus-1-queries]]></category>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[entity-graph]]></category>
            <dc:creator><![CDATA[Dinakaran Ramadurai]]></dc:creator>
            <pubDate>Sat, 24 Sep 2022 09:52:54 GMT</pubDate>
            <atom:updated>2022-09-24T09:52:54.391Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring JPA generating many queries : n+1 query problem</h3><p>If you are using JPA and you haven’t seen this problem then you haven’t fully understood how jpa works internally yet. To understand and learn how JPA works internally as a first step you need to add the below property in application.properties of spring boot application</p><blockquote><strong>spring.jpa.show-sql: true</strong></blockquote><p>Lets try to create this problem. Consider a below database design with one to many relationship between tweet and comments</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*vRjhOinRb8kDI0_LGB86SQ.png" /><figcaption>Database design. Tweet -&gt; comments (One to many realtionship)</figcaption></figure><p>Please find below the entity class of the ablove design so that we all are in same page</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23b2cf8b09adb0d6714c60699fb3e420/href">https://medium.com/media/23b2cf8b09adb0d6714c60699fb3e420/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eddd38dc9be6a8e7e03c0be7b1d1130f/href">https://medium.com/media/eddd38dc9be6a8e7e03c0be7b1d1130f/href</a></iframe><p>Now Lets insert some sample data into tweets table and comments table. Tweet table has 4 tweets and each tweet has some comments added to it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fYQiEtiMRtHxvDxh6FxD7w.png" /><figcaption>sample date into tweet and comments table</figcaption></figure><p>Nows lets try to pull all the tweets that starts with D and comments associated with it. Just pause and think how the query will be formed by jpa and how much query does it creates to fetch the tweets with comments?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ed97c24154357b4ea9b8ef0201c24d2/href">https://medium.com/media/8ed97c24154357b4ea9b8ef0201c24d2/href</a></iframe><p>Run the above jpa query and print the tweet and comments associated with it. Boom you will see 5 queries executed by JPA. one to retrieve tweet and other 4 to retrieve comments associated with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a1AqyXqp1dDtsO78T36osg.png" /><figcaption>Queries run by JPA to fetch tweet and comments</figcaption></figure><p>Okay I am hearning what you are thinking -&gt; why JPA is doing this to me right? Instead of runing one query to retrieve 4(n) values from database it is taking 5(n+1) queries which explains why n+1 name.</p><h3><strong>Reasons for n+1 query problem</strong></h3><blockquote><strong>FetchType.LAZY</strong></blockquote><p>Since comment is fetched lazily, a second SQL query will be executed to get the comments associated for each tweet. you can catch the same in query log that comments query uses where condition tweet_id = ?. This implies it is forming comments query for each tweets we retrieved</p><blockquote><strong>FetchType.EAGER</strong></blockquote><p>Okay hearing again use eager fetching why to use this. Try that it will generate 5 queeies in that case well because tweet values has to be fetched before comments by JPA to pull comments values from database. Using FetchType.EAGER either implicitly or explicitly for your JPA associations is a bad idea because you are going to fetch way more data that you need. More, the FetchType.EAGER strategy is also prone to N+1 query issues.</p><h3><strong>How to solve n+1 query problem</strong></h3><p>Entity Graph comes to the rescue. JPA 2.1 introduces it and provies a better way to handle this performance issue. Now we have to tell JPA to fetch comments record also while retrieving Tweets record. That is we have to join fetch the records from both tweets table and comments table.</p><p>Lets do the below change in repository class. Above the JPA query specify the fields you have to join fetch with tweets and wait for tha magic to happen</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f0016ebb75e946d9d56d7ce615fd54e/href">https://medium.com/media/2f0016ebb75e946d9d56d7ce615fd54e/href</a></iframe><p>Magic Happened? you will see that JPA fetched Tweets and associated comments with it using one query and the records got fetched in less than second. Please find below the executed query</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ECaihc8nvffgR4xTUKVow.png" /><figcaption>Query after adding field in entity graph annotation</figcaption></figure><h3><strong>Performace Boost table</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*p98-JIfQcsyoZB4yRIzs7g.png" /><figcaption>Time taken before and after fixing n+1 query problem</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*TaflJiY5ooJ2dUImG8xJSQ.png" /><figcaption>Performace impact of before fixing n+1 query vs after fixing it</figcaption></figure><h3><strong>Conclusion</strong></h3><p>JPA fetches all the fields that are specified in the attribute path array of entity graph. This is considered to be a good performance.</p><p>The JPA documentation recommends using the <em>FetchType.LAZY</em> strategy whenever possible, and the Entity Graph when we need to load an association.</p><p>Please find my Gihub repo for the code <a href="https://github.com/dinakaranram9/medium-jpa">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a54a5da5bca3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>