<?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 Vikram on Medium]]></title>
        <description><![CDATA[Stories by Vikram on Medium]]></description>
        <link>https://medium.com/@sendvjs?source=rss-3ec6a97bfa28------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Vikram on Medium</title>
            <link>https://medium.com/@sendvjs?source=rss-3ec6a97bfa28------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:51:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sendvjs/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[Spring Bean Life Cycle]]></title>
            <link>https://medium.com/@sendvjs/spring-bean-life-cycle-9363332c335e?source=rss-3ec6a97bfa28------2</link>
            <guid isPermaLink="false">https://medium.com/p/9363332c335e</guid>
            <category><![CDATA[beans]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[bean-life-cycle]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[lifecycle]]></category>
            <dc:creator><![CDATA[Vikram]]></dc:creator>
            <pubDate>Fri, 28 Jul 2023 01:59:23 GMT</pubDate>
            <atom:updated>2023-07-28T01:59:23.273Z</atom:updated>
            <content:encoded><![CDATA[<p>In the context of Spring Framework, if we want to execute some code after the bean construction, then we can write that code inside the custom <strong>init()</strong> method. Similarly, if we want to execute some code just before the destruction of the bean, we can write that code inside <strong>destroy()</strong> method. These methods are called Spring Bean Life Cycle Methods. Here in this article we will develop ‘Spring Bean Life Cycle Method Examples’. The bean life cycle is managed by the spring container. When we run the program, first of all, the spring container gets started. After that, the container creates the instance of a bean as per the request, and then the required dependencies are injected. At the end, the bean is destroyed when the spring container is closed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*5MShKzJV3ClbCRHHWxIWIw.png" /><figcaption>Life cycle</figcaption></figure><h3>What is Bean Life Cycle?</h3><p>When we talk about the life cycle of a living thing as a general term, It means when &amp; how it is born, how &amp; what it has done throughout its life, and when &amp; how it has died. Similarly, the bean life cycle refers to when &amp; how the bean is instantiated, what action it performs until it lives, and when &amp; how it is destroyed.</p><h3>What are Spring Bean Life Cycle Methods?</h3><p>When a Spring Container creates a bean, it provides two methods to every bean by default. These are:</p><p>1) public void init() 2) public void destroy()</p><p>However, we can change the names of methods, but method signature must be the same. If we remain the method names as it is, the code becomes easy to understand.</p><h3>When are the Bean Life Cycle Methods called?</h3><p>The init() method is called after bean construction and before requesting an object. destroy() method is called just before the destruction of a bean.</p><h3>What are the purpose of implementing Life Cycle Methods?</h3><p>init(): If we want to initialize anything such as loading some configurations, creating database connections, we can write that code in init() method.</p><p>destroy(): If we want to cleanup something such as closing database connections, we can write that code in destroy() method.</p><h3>What are the different approaches to configure Spring Bean Life Cycle Methods?</h3><p>There are three approaches to configure Spring Bean Life Cycle methods:</p><p>1) Using XML (also called Declarative Approach)</p><p>2) Using Spring Interfaces (also called Programmatic Approach)</p><p>3) Using Annotations</p><p>Now let’s create some examples to understand Spring Bean Life Cycle methods.</p><h3>How to implement Spring Bean Life Cycle Method Examples Using XML Configuration?</h3><p>Let’s start implementing an example using XML configuration step by step:</p><h3>Step#1: Create a Project in Eclipse/STS</h3><p>1) Open your Eclipse IDE, then go to new -&gt; project-&gt; Maven Project and click on next.</p><p>2) Click on ‘Create a simple Project (Skip archetype selection)’</p><p>3) Provide the values of Group Id &amp; Artifact Id. Group Id uniquely identifies your project among all. So it may be something like com.dev.spring.lifecycle. Artifact Id may be something like project name, so here we can put artifact id as SpringLifeCycleExample.</p><p>4) Click on ‘Finish’. You will get a new maven based project.</p><h3>Step#2: Modify pom.xml</h3><p>When you create a new project, you will find a file called pom.xml. In this file we need to provide the dependency of basic spring jars. Copy the below code and paste it in your pom.xml inside &lt;dependencies&gt; tag. You can choose to provide the latest stable version of your own choice.</p><pre>&lt;dependency&gt;<br>     &lt;groupId&gt;org.springframework&lt;/groupId&gt;<br>     &lt;artifactId&gt;spring-core&lt;/artifactId&gt;<br>     &lt;version&gt;4.1.4.RELEASE&lt;/version&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-context&lt;/artifactId&gt;<br>    &lt;version&gt;4.1.4.RELEASE&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Once you save the pom.xml file, all required jars will get downloaded automatically.</p><h3>Step#3: Create a Pojo Class</h3><p>Let’s create a package com.dev.spring.bean.lifecycle inside ‘src/main/java’ folder of your project explorer. Then create a POJO class Book.java under this package as shown below.</p><pre>package com.dev.spring.bean.lifecycle;</pre><pre>public class Book {</pre><pre>   private Integer id;<br>   private String name;</pre><pre>   public Book() {<br>      super();<br>   }<br> <br>   public Integer getId() {<br>      return id;<br>   }<br>   public void setId(Integer id) {<br>      System.out.println(&quot;Setting Book Id&quot;);<br>      this.id = id;<br>   }<br>   public String getName() {<br>      return name;<br>   }<br>   public void setName(String name) {<br>      this.name = name;<br>   }</pre><pre>   @Override<br>   public String toString() {<br>      return &quot;Book [Id=&quot; + Id + &quot;, name=&quot; + name + &quot;]&quot;;<br>   }</pre><pre>   public void initMethod() {<br>      System.out.println(&quot;Inside init() method&quot;);<br>   }</pre><pre>   public void destroyMethod() {<br>      System.out.println(&quot;Inside destroy() method&quot;);<br>   }<br>}</pre><p>Here, we have created two methods initMethod() and destroyMethod(), which will be our bean life cycle methods.</p><h3>Step#4: Create a configuration file (config.xml)</h3><p>This file is important as we are using XML method to implement bean life cycle methods. Apart from defining the bean, most importantly, we need to provide init-method name and destroy-method name which we provided in our class as shown below.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;<br>xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>xmlns:context=&quot;http://www.springframework.org/schema/context&quot; xsi:schemaLocation=&quot;<br>http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd<br>http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd&quot;&gt;</pre><pre>&lt;!-- bean definitions here --&gt;</pre><pre>&lt;bean name=&quot;book&quot; class=&quot;com.dev.spring.bean.lifecycle.Book&quot;<br>                  init-method=&quot;initMethod&quot; destroy-method=&quot;destroyMethod&quot;&gt;<br>  &lt;property name=&quot;id&quot; value=&quot;94568&quot;/&gt;<br>  &lt;property name=&quot;name&quot; value=&quot;Spring In Action&quot;/&gt;<br>&lt;/bean&gt;</pre><pre>&lt;/beans&gt;</pre><p>While creating XML configuration file, we can refer <a href="https://docs.spring.io/spring-framework/docs/4.2.x/spring-framework-reference/html/xsd-configuration.html">Spring docs for XSD Configuration</a> to get the proper schema definitions. Since we are going to use beans &amp; context module of Spring framework, we have added schema definitions only for them.</p><h3>Step#5: Create a Test class</h3><p>Let’s create a test class where we will define a main() method to test our results.</p><pre>package com.dev.spring.bean.lifecycle;</pre><pre>import org.springframework.context.support.AbstractApplicationContext;<br>import org.springframework.context.support.ClassPathXmlApplicationContext;</pre><pre>public class Test {</pre><pre>public static void main(String[] args) {</pre><pre>   // ApplicationContext ctx= new ClassPathXmlApplicationContext(&quot;com/dev/spring/bean/lifecycle/config.xml&quot;);<br>   AbstractApplicationContext ctx= new ClassPathXmlApplicationContext(&quot;com/dev/spring/bean/lifecycle/config.xml&quot;);<br>   Book book = (Book) ctx.getBean(&quot;book&quot;);<br>   System.out.println(book);</pre><pre>   //registering shutdown hook<br>   ctx.registerShutdownHook();<br>   }<br>}</pre><p>In order to use destroy method of spring bean life cycle, we need to call registerShutdownHook() method. This method is available in AbstractApplicationContext. Hence, we are using AbstractApplicationContext interface in place of ApplicationContext interface to get spring context.</p><h3>Step#6: Test Output</h3><p>Once you run the application, output will look like below:</p><pre>Setting Book Id<br>Inside init() method<br>Book [Id=94568, name=Spring In Action]<br>Inside destroy() method</pre><p>Form the output, it is clear that first of all properties are getting set, then init() method is called. At the last destroy() method is called.</p><h3>How to implement Spring Bean Life Cycle Method Examples Using Spring Interfaces?</h3><p>Spring Framework provides two interfaces to implement Spring Bean Life <strong>Cycle methods:</strong></p><p>InitializingBean</p><p>DisposableBean</p><h3>Step#1: Create a Project &amp; Update pom.xml</h3><p>Please complete Step#1 &amp; Step#2 from the previous section if not already done.</p><h3>Step#2: Create a Pojo Class</h3><p>Here, we have to create a POJO class that will implement Spring provided two interfaces: InitializingBean &amp; DisposableBean as shown below.</p><pre>package com.dev.spring.bean.lifecycle;</pre><pre>import org.springframework.beans.factory.DisposableBean;<br>import org.springframework.beans.factory.InitializingBean;</pre><pre>public class Employee implements InitializingBean, DisposableBean{</pre><pre>   private Long id;<br>   private String name;</pre><pre>   public Employee() {<br>     super();<br>   }</pre><pre>   public Long getId() {<br>      return id;<br>   }<br>   public void setId(Long id) {<br>      System.out.println(&quot;Setting Id Of the Employee&quot;);<br>      this.id = id;<br>   }<br>   public String getName() {<br>      return name;<br>   }<br>   public void setName(String name) {<br>      this.name = name;<br>   }</pre><pre>   @Override<br>   public String toString() {<br>      return &quot;Employee [id=&quot; + id + &quot;, name=&quot; + name + &quot;]&quot;;<br>   }</pre><pre>   public void afterPropertiesSet() throws Exception {</pre><pre>      System.out.println(&quot;Inside afterPropertiesSet() method&quot;);<br>   }</pre><pre>   public void destroy() throws Exception {</pre><pre>      System.out.println(&quot;Inside destroy() method&quot;);<br>   }<br>}</pre><p>When you implement two interfaces, compiler will expect from you to override spring life cycle methods: afterPropertiesSet() and destroy().</p><h3>Step#3: Create a configuration file (config.xml)</h3><p>This file is important as we are going to define bean here.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;<br>xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>xmlns:context=&quot;http://www.springframework.org/schema/context&quot; xsi:schemaLocation=&quot;<br>http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd<br>http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd&quot;&gt;</pre><pre>&lt;!-- bean definitions here --&gt;</pre><pre>&lt;bean name=&quot;employee&quot; class=&quot;com.dev.spring.bean.lifecycle.Employee&quot;&gt;<br>    &lt;property name=&quot;id&quot; value=&quot;74568&quot;/&gt;<br>    &lt;property name=&quot;name&quot; value=&quot;Employee-1&quot;/&gt;<br>&lt;/bean&gt;</pre><pre>&lt;/beans&gt;</pre><p>While creating XML configuration file, we can refer <a href="https://docs.spring.io/spring-framework/docs/4.2.x/spring-framework-reference/html/xsd-configuration.html">Spring docs for XSD Configuration</a> to get the proper schema definitions. Since we are going to use beans &amp; context module of Spring framework, we have added schema definitions only for them.</p><h3>Step#4: Create a Test class</h3><p>Let’s create a test class where we will define a main() method to test our results.</p><pre>package com.dev.spring.bean.lifecycle;</pre><pre>import org.springframework.context.support.AbstractApplicationContext;<br>import org.springframework.context.support.ClassPathXmlApplicationContext;</pre><pre>public class Test {</pre><pre>public static void main(String[] args) {</pre><pre>   // ApplicationContext ctx= new ClassPathXmlApplicationContext(&quot;com/dev/spring/bean/lifecycle/config.xml&quot;);<br>   AbstractApplicationContext ctx= new ClassPathXmlApplicationContext(&quot;com/dev/spring/bean/lifecycle/config.xml&quot;);<br>   Employee employee = (Employee) ctx.getBean(&quot;employee&quot;);<br>   System.out.println(employee);</pre><pre>   //registering shutdown hook<br>   ctx.registerShutdownHook();<br>   }<br>}</pre><p>In order to use destroy method of spring bean life cycle, we need to call registerShutdownHook() method. This method is available in AbstractApplicationContext. Hence, we are using AbstractApplicationContext interface in place of ApplicationContext interface to get spring context.</p><h3>Step#5: Test Output</h3><p>Once you run the application, output will look like below:</p><pre>Setting Id Of the Employee<br>Inside afterPropertiesSet() method<br>Employee [id=74568, name=Employee-1]<br>Inside destroy() method</pre><p>Form the output, it is clear that first of all properties are getting set, then afterPropertiesSet() method is called. At the last destroy() method is called.</p><h3>How to implement Spring Bean Life Cycle Method Examples Using Annotations?</h3><p>Spring framework provides two annotations to implement bean life cycle in Spring:</p><p>@PostConstruct</p><p>@PreDestroy</p><p>Annotation names are self explanatory. PostConstructs means after constructing the properties of the class. PreDestroy means before destroying the bean.</p><h3>Step#1: Create a Project in Eclipse/STS</h3><p>Please complete Step#1 from the previous sections if not already done.</p><h3>Step#2: Modify pom.xml</h3><p>When you create a new project, you will find a file called pom.xml. In this file we need to provide the dependency of basic spring jars. Copy the below code and paste it in your pom.xml inside &lt;dependencies&gt; tag. You can choose to provide the latest stable version of your own choice.</p><p>One important point here is to note that both the @PostConstruct and @PreDestroy annotations do not belong to the Spring. They are part of Jave EE (JEE) library and exits in common-annotations.jar. Since Java EE was deprecated in Java 9, and removed in Java 11, we have to add an additional dependency ‘javax.annotation-api’ to use these annotations. If you are using Java 8 or lower versions, there is no need to include this dependency.</p><pre>&lt;dependency&gt;<br>     &lt;groupId&gt;org.springframework&lt;/groupId&gt;<br>     &lt;artifactId&gt;spring-core&lt;/artifactId&gt;<br>     &lt;version&gt;4.1.4.RELEASE&lt;/version&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-context&lt;/artifactId&gt;<br>    &lt;version&gt;4.1.4.RELEASE&lt;/version&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;javax.annotation&lt;/groupId&gt;<br>    &lt;artifactId&gt;javax.annotation-api&lt;/artifactId&gt;<br>    &lt;version&gt;1.3.2&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Once you save the pom.xml file, all required jars will get downloaded automatically.</p><h3>Step#2: Create a Pojo Class</h3><p>Here, we have to create a POJO class that will have two life cycle methods where we will use annotations: @PostConstruct &amp; @PreDestroy as shown below.</p><pre>package com.dev.spring.bean.lifecycle;</pre><pre>import javax.annotation.PostConstruct;<br>import javax.annotation.PreDestroy;</pre><pre>public class Person {</pre><pre>   private String name;<br>   private Integer age;</pre><pre>   public Person() {<br>      super();<br>   }</pre><pre>   public String getName() {<br>      return name;<br>   }</pre><pre>   public void setName(String name) {<br>     this.name = name;<br>   }</pre><pre>   public Integer getAge() {<br>      return age;<br>   }</pre><pre>   public void setAge(Integer age) {<br>      System.out.println(&quot;Setting Person&#39;s Age&quot;);<br>      this.age = age;<br>   }</pre><pre>   @Override<br>   public String toString() {<br>      return &quot;Person [name=&quot; + name + &quot;, age=&quot; + age + &quot;]&quot;;<br>   }</pre><pre>   @PostConstruct<br>   public void initMethod() {<br>      System.out.println(&quot;Inside init method&quot;);<br>   }</pre><pre>   @PreDestroy<br>   public void destroyMethod() {<br>      System.out.println(&quot;Inside destroy method&quot;);<br>   }<br>}</pre><p>When you implement two life cycle methods, don’t forget to annotate them.</p><h3>Step#3: Create a configuration file (config.xml)</h3><p>Apart from defining the bean, we need to specify &lt;context:annotation-config/&gt; tag here. It will enable annotations in the application. Please note that without this tag, you will not be able to use annotations in your application.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;<br>xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>xmlns:context=&quot;http://www.springframework.org/schema/context&quot; xsi:schemaLocation=&quot;<br>http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd<br>http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd&quot;&gt;</pre><pre>&lt;!-- bean definitions here --&gt;<br>&lt;context:annotation-config/&gt;</pre><pre>&lt;bean name=&quot;person&quot; class=&quot;com.dev.spring.bean.lifecycle.Person&quot;&gt;<br>    &lt;property name=&quot;age&quot; value=&quot;24&quot;/&gt;<br>    &lt;property name=&quot;name&quot; value=&quot;Person-1&quot;/&gt;<br>&lt;/bean&gt;</pre><pre>&lt;/beans&gt;</pre><p>While creating XML configuration file, we can refer <a href="https://docs.spring.io/spring-framework/docs/4.2.x/spring-framework-reference/html/xsd-configuration.html">Spring docs for XSD Configuration</a> to get the proper schema definitions. Since we are going to use beans &amp; context module of Spring framework, we have added schema definitions only for them.</p><h3>Step#4: Create a Test class</h3><p>Let’s create a test class where we will define a main() method to test our results.</p><pre>package com.dev.spring.bean.lifecycle;</pre><pre>import org.springframework.context.support.AbstractApplicationContext;<br>import org.springframework.context.support.ClassPathXmlApplicationContext;</pre><pre>public class Test {</pre><pre>public static void main(String[] args) {</pre><pre>   // ApplicationContext ctx= new ClassPathXmlApplicationContext(&quot;com/dev/spring/bean/lifecycle/config.xml&quot;);<br>   AbstractApplicationContext ctx= new ClassPathXmlApplicationContext(&quot;com/dev/spring/bean/lifecycle/config.xml&quot;);<br>   Person person = (Person) ctx.getBean(&quot;person&quot;);<br>   System.out.println(person);</pre><pre>   //registering shutdown hook<br>   ctx.registerShutdownHook();<br>   }<br>}</pre><p>In order to use destroy method of spring bean life cycle, we need to call registerShutdownHook() method. This method is available in AbstractApplicationContext. Hence, we are using AbstractApplicationContext interface in place of ApplicationContext interface to get spring context.</p><h3>Step#5: Test Output</h3><p>Once you run the application, output will look like below:</p><pre>Setting Person&#39;s Age<br>Inside init method<br>Person [name=Person-1, age=24]<br>Inside destroy method</pre><p>Form the output, it is clear that first of all properties are getting set, then init() method is called. At the last destroy() method is called.</p><h3>FAQ</h3><h3>When to use Which Approach of Spring Bean Life Cycle Methods?</h3><p>The decision on the approach should be based on the specific scenario:</p><p>1) If the Spring Bean is a user-defined class, we should prefer the annotation based approach, because we can easily add annotations in the source code of user-defined classes.</p><p>2) If the Spring Bean is a predefined Java class provided by the Spring Framework, and also implementing InitializingBean, DisposableBean interfaces, then it automatically goes for interfaces approach, otherwise go with XML based approach by identifying the life cycle methods.</p><p>3) If the Spring Bean is a pre-defined class provided by third party or JDK/JEE, then we should go with the XML approach by identifying the life cycle methods.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9363332c335e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GIT CHEAT SHEET]]></title>
            <link>https://medium.com/@sendvjs/git-cheat-sheet-f4ee07a66e86?source=rss-3ec6a97bfa28------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4ee07a66e86</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[cheatsheet]]></category>
            <dc:creator><![CDATA[Vikram]]></dc:creator>
            <pubDate>Sat, 22 Jul 2023 11:46:15 GMT</pubDate>
            <atom:updated>2023-07-22T11:46:15.794Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8DaR4oiMyFhdsdINVD0ZA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zt-WY36VGmqtr5tB4X_2rw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0KLfPsjoSDQyd6katidZTw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cp33RVcpscAnPoJZ1ypzpg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n2AdYIdFXdGqOwrzK5bAsg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*84Jc6sUjvewQs4A9LodXPg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4uwd57DgNZ1mliDKNhY3QA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XpxZj9xdOrEsx9EXGJeNiw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*699NIxuY_tvOzUadkYddpA.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4ee07a66e86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cron Expression — Sprint Boot]]></title>
            <link>https://medium.com/@sendvjs/cron-expression-sprint-boot-5112d1aed830?source=rss-3ec6a97bfa28------2</link>
            <guid isPermaLink="false">https://medium.com/p/5112d1aed830</guid>
            <category><![CDATA[cron-expression]]></category>
            <dc:creator><![CDATA[Vikram]]></dc:creator>
            <pubDate>Sun, 13 Nov 2022 07:06:00 GMT</pubDate>
            <atom:updated>2022-11-13T07:14:43.079Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Cron Expression — Sprint Boot</strong></h3><p><strong>How To Schedule A Task/Job In Java? : Spring Boot Scheduler</strong></p><p>Sometimes we come across a situation when we expect a task should execute only at a particular point of time or re-execute within a particular time interval. Simultaneously, our client expects a functionality to be executed at a particular time on an hourly basis, daily basis, weekly basis, monthly basis or even some other as well. In fact, in all these types of situations we implement scheduling to get the requirements fulfilled accordingly. For example, one of the most popular implementation is the report generation at a particular time.</p><p>On the other hand, almost every client expects this functionality to have in the project. Currently the most popular one is the PDF report export. Consequently, our topic ‘How to Schedule a Task/Job in Java? : Spring Boot Scheduler’ will provide a complete answer on how to do Scheduling using Spring Boot.</p><p>Spring Boot has the best support for scheduling wherein we can implement the same in easy &amp; straightforward steps accordingly. There is nothing to explain more on the need of topic ‘How to Schedule a Task/Job in Java : Spring Boot Scheduler’. Also, every Java developer in his/her professional life will come across this type of scenarios where scheduling will help to solve the project requirement easily. Hence, let’s talk about our topic ‘How to Schedule a Task/Job in Java? : Spring Boot Scheduler’.</p><p><strong>What is scheduling and where is it used ?</strong></p><p>In a sentence, Scheduling is a process in which we can execute a task in a particular time interval without human intervention. In other words, we can say Scheduling is a process of Executing a task in a loop based on period of time or point of time. For example, suppose our task is to generate a report everyday at 9:30AM. Then we can apply scheduling technique here to fulfill our requirements accordingly.</p><p>As another example, if we want to send a particular data or file to other application in a particular time interval, then we can do it by using scheduling. Furthermore, places where we can use scheduling are Monthly Bank Statements, Salary Slip generation, Insurance Payment, Electricity Bill, Daily Stand up meetings in Offices, Sprint Planning etc.</p><p><strong>What is difference between Period of time &amp; Point of time ?</strong></p><p>Period of time talks about a time gap. It doesn’t have starting date/time. eg. 1 hour, 24 mins, 3 days, 4 months, 40 seconds etc.</p><p>Point of time talks about a particular time. Moreover, it has staring date/time. eg. 4 AM, 15th Aug, 26th Jan 9:00AM etc.</p><p><strong>How to implement Scheduling in Spring Boot : Steps ?</strong></p><p><strong>Step#1</strong> : Create spring boot starter project : No need to add any other starter dependency.</p><p><strong>Step#2</strong> : At Starter class apply @EnableScheduling</p><p><strong>Step#3</strong> : Additionally, define a class and apply @Component over class</p><p><strong>Step#4</strong> : Finally, Implement a method in above class accordingly, which executes the task and apply @Scheduled(……………)</p><p><strong>What is the functionality of @Scheduled?</strong></p><p>This annotation instructs Spring Container to execute the method in a loop as per the provided parameters until the application/server stops. However, it uses below concepts to support scheduling.<br> 1) fixed Delay<br> 2) fixed Rate<br> 3) cron expression</p><p><strong>Note:</strong> Equally important, You can’t write @Scheduled without any input in the bracket, other wise Spring container will throw IllegalStateException: Encountered invalid @Scheduled method ‘generateReport’: Exactly one of the ‘cron’, ‘fixedDelay(String)’, or ‘fixedRate(String)’ attributes is required.</p><p><strong>Which Methods can be the candidate to use @Scheduled?</strong></p><p>@Scheduled is a method level annotation applied at runtime to mark the method to be scheduled. Any method using @Scheduled needs to satisfy two conditions:</p><p>1) The annotated method should not have a return type. Otherwise the return value will be overlooked at runtime.</p><p>2) The annotated method should not accept any input parameters.</p><p><strong>Examples of a Scheduled Task using Spring Boot Scheduler</strong></p><p>We will see the examples of all three concepts but cron expression is the mostly used concept in the industry. fixedRate and fixedDelay supports period of time. However, Cron expression supports both period of time &amp; point of time.</p><p><strong>Using fixedDelay</strong></p><p>Fixed delay specifies exact time gap between last method execution completion time and next method start time. On application startup scheduling also starts without time gap. Furthermore, to provide the time gap before first execution call, use initialDelay. For example, observe the code snippets below:</p><p>@EnableScheduling<br> @SpringBootApplication<br> @EnableScheduling<br> public class SpringBootSchedulingApplication {</p><p>public static void main(String[] args) {<br> SpringApplication.run(SpringBootSchedulingApplication.class, args);<br> }</p><p>}</p><p>SchedulerServiceOne.java</p><p>package com.dev.springboot.scheduling;</p><p>import java.util.Date;</p><p>import org.springframework.scheduling.annotation.Scheduled;<br> import org.springframework.stereotype.Component;</p><p>@Component<br> public class SchedulerServiceOne {<br> <br> @Scheduled(initialDelay = 5000, fixedDelay = 9000) <br> // @Scheduled(initialDelayString = “5000” ,fixedDelayString = “9000”)<br> // 1000 milli sec = 1sec<br> public void scheduledMethod() {<br> System.out.println(“Hello Scheduler One :” +new Date());<br> }<br> }</p><p>Note: We can provide fixedDelay input in two ways : Integer and String (To illustrate, look at the above code example)<br> Integer type : @Scheduled(fixedDelay = 1000)<br> String type : @Scheduled(fixedDelayString = “1000”)</p><p><strong>Using fixedRate</strong></p><p>However, fixedRate denotes the maximum time gap between method call.</p><p>SchedulerServiceTwo.java</p><p>package com.dev.springboot.scheduling;</p><p>import java.util.Date;</p><p>import org.springframework.scheduling.annotation.Scheduled;<br> import org.springframework.stereotype.Component;</p><p>@Component<br> public class SchedulerServiceTwo {</p><p>@Scheduled(fixedRate=1000)<br> //@Scheduled(fixedRateString = “4000”)<br> public void scheduledMethod() {<br> System.out.println(“Hello Scheduler Two :” +new Date());<br> }<br> }</p><p><strong>Using cron expression</strong></p><p>As Cron Expressions are very popular in Unix/Linux OS for scheduling, here also Spring boot includes the same concept internally.</p><p>SchedulerServiceThree.java</p><p>package com.dev.springboot.scheduling;</p><p>import java.util.Date;</p><p>import org.springframework.scheduling.annotation.Scheduled;<br> import org.springframework.stereotype.Component;</p><p>@Component<br> public class SchedulerServiceThree {</p><p>@Scheduled(cron = “15 * * * * *”)<br> public void scheduledMethod() {<br> System.out.println(“Hello cron Scheduler Three :” +new Date());<br> }<br> }</p><p><strong>How to write a Cron Expression ?</strong></p><ol><li>There are 6 Asterisks(******) by default in cron expression as shown below. Further each asterisk has some meaning as they denote a value. These values can be assigned as Second, Minute, Hours, Day, Month, WeekDay respectively in sequence as shown below.<br> Possible values at proper place are also given below.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*Xb1ZKvFh4VHrWW3T9naeTg.png" /></figure><p>2) A Cron Expression can accept symbols : <strong>* — , / ?</strong></p><p>3) <strong>Comma</strong> denotes passible values<br> 0 0 4,6 * * *<br> Above expression denotes ‘execute given task every day 4:00:00AM and 6:00:00 AM</p><p>4) <strong>Dash (-)</strong> denotes a range which means consider all possible values between the range<br> 0 0 4–6 * * *<br> To illustrate, above expression just denotes ‘execute given task every day 4:00:00AM, 5:00:00AM and 6:00:00 AM’</p><p>5) <strong>Asterisk(*)</strong> denotes any/every/all value</p><p>6) <strong>Forward slash(/)</strong> denotes period of time</p><p>7) <strong>Question mark(?)</strong> denotes any value but it is applied only at Day &amp; WeekDay when month value is given.</p><p>8) English names can also be used for the day-of-month and day-of-week fields. Use the first three letters of the particular day or month (case does not matter).</p><p><strong>Cron Expression Exercise with Examples using Spring Boot Scheduler</strong></p><p>From the above explanation we learned how to write a cron expression. Consequently, let’s do some exercise on cron expression to make it solid.</p><p><strong>Examples Using Point of Time</strong></p><p><strong>Ex#1</strong> : Write a cron expression that executes a task everyday at 8 AM</p><p>0 0 8 * * *</p><p>From the above explanation we learned how to write a cron expression. Consequently, let’s do some exercise on cron expression to make it solid.</p><p><strong>Examples Using Point of Time</strong></p><p><strong>Ex#1</strong> : Write a cron expression that executes a task everyday at 8 AM</p><p>0 0 8 * * *</p><p><strong>Ex#2</strong> : Write a cron expression that executes a task everyday at 4 PM</p><p>0 0 16 * * *</p><p><strong>Ex#3</strong> : Write a cron expression that executes a task at 9AM and 9PM every day</p><p>0 0 9,21 * * *</p><p><strong>Ex#4</strong> : Write a cron expression that executes a task at 9AM and 8PM every day</p><p>0 0 9,20 * * *</p><p><strong>Ex#5</strong> : Write a cron expression that executes a task at 8AM, 9AM, 10AM and 11AM every day</p><p>0 0 8–11 * * *</p><p><strong>Ex#6</strong> : Write a cron expression that executes a task 4 times each after one hour, first at 9PM everyday</p><p>0 0 21–00 * * *</p><p><strong>Ex#7</strong> : Write a cron expression that executes a task 4 times each after one hour, first at 9PM everyday</p><p>0 0 21–00 * * * OR 0 0 21,22,23,00 * * *</p><p><strong>Ex#8</strong> : Write a cron expression that executes a task 6:30AM and 9:30PM everyday</p><p>0 30 6,21 * * *</p><p><strong>Ex#9</strong> : Write a cron expression that executes a task at 0th minute and 0th second</p><p>0 0 * * * * ( task will be executed at 00:00:00, 01:00:00, 02:00:00, 03:00:00, ……………….23:00:00)</p><p><strong>Ex#10</strong> : Write a cron expression that executes a task every minute at 15th second</p><p>15 * * * * * ( task will be executed at 00:00:15, 00:01:15, 00:02:15, 00:03:15, ……………….00:59:15, 01:00:15, 01:01:15…..etc.)</p><p><strong>Ex#11</strong> : Write a cron expression that executes a task 9AM 15th second(9:00:45 AM) every day</p><p>15 0 0 * * *</p><p><strong>Ex#12</strong> : Write a cron expression that executes a task every year on Aug 25th 9AM</p><p>0 0 9 25 8 *</p><p><strong>Ex#13</strong> : Write a cron expression that executes a task every month on 7th day at 9:30 AM</p><p>0 30 9 7 * *</p><p><strong>Ex#14</strong> : Write a cron expression that executes a task every year on Feb 14th 9:00:00 AM<br> if given day(14th) is Sunday or Tuesday only.</p><p>0 0 9 14 2 SUN,TUE</p><p><strong>Ex#15 :</strong> Write a cron expression that executes a task every year in April everyday at 8AM.</p><p>0 0 8 ? 4 ? OR 0 0 8 * 4 *</p><p><strong>Note : </strong>If month is given, we can use symbol ? in place of * for days &amp; week days.</p><p><strong>Ex#16</strong> : How to write a cron expression that executes a task every year to wish a happy new year.</p><p>59 59 23 31 12 * OR 0 0 0 1 1 *</p><p><strong>Ex#17</strong> : How to write a cron expression that executes a task every year to wish happy birthday on 30th March.</p><p>59 59 23 29 3 * OR 0 0 0 30 3 *</p><p><strong>Ex#18</strong> : How to write a cron expression that executes a task on the hour 9AM to 6PM weekdays.</p><p>0 0 8–18 * * MON-FRI</p><p><strong>Examples Using Period of Time</strong></p><p>Use slash(/) for period of time at all positions except week days.</p><p><strong>Ex#1</strong> : How to write a cron expression that executes a task for every 15 sec gap.</p><p>*/15 * * * * *</p><p><strong>Ex#2</strong> : How to write a cron expression that executes a task for starting of execution at 0th sec of every minute<br> and also execute with 30 sec gap</p><p>0/30 * * * * *</p><p><strong>Ex#3</strong> : How to write a cron expression that executes a task for Every day 11AM and repeat with a gap of 30 min</p><p>0 0/30 11 * * * (task will be executed at 11:00:00 AM, 11:30:00 AM, then next day at 11:00:00 AM and so on…)</p><p><strong>Ex#4</strong> : How to write a cron expression that executes a task for Every hour 0th min &amp; 0th sec with a gap of 20 secs</p><p>0 0/20 * * * *</p><p><strong>Ex#5</strong> : At what time the task will be executed by cron expression : <strong>0 0/30 8–10 * * *</strong></p><p><strong>Ans: </strong>8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day</p><p><strong>Ex#6</strong> : At what time the task will be executed by cron expression : <strong>0/20 30/10 10 * * *</strong></p><p><strong>Examples of Invalid cron expressions</strong></p><p><strong>Ex#1</strong> : <strong>0 * 10 * * *</strong></p><p>Of course above cron expression is invalid. Once Asterisk Symbol (*) is used, then next position values are not allowed which makes expression invalid.</p><p><strong>Ex#2</strong> : <strong>* 0 10 * * *</strong> is invalid for the same reason as mentioned above.</p><p>— — — — — — — — — — — — END — — — — — — — — — — — —</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5112d1aed830" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Operators, Functions, Expressions, Conditions]]></title>
            <link>https://medium.com/@sendvjs/operators-functions-expressions-conditions-36b076990e8b?source=rss-3ec6a97bfa28------2</link>
            <guid isPermaLink="false">https://medium.com/p/36b076990e8b</guid>
            <dc:creator><![CDATA[Vikram]]></dc:creator>
            <pubDate>Sat, 10 Oct 2020 19:26:29 GMT</pubDate>
            <atom:updated>2020-10-10T19:26:29.366Z</atom:updated>
            <content:encoded><![CDATA[<p>This chapter describes methods of manipulating individual data items. Standard arithmetic operators such as addition and subtraction are discussed, as well as less common functions such as absolute value and string length. Topics include:</p><ul><li><a href="http://www.pitt.edu/~hoffman/oradoc/server.804/a58225/ch3all.htm#997665">Operators</a></li><li><a href="http://www.pitt.edu/~hoffman/oradoc/server.804/a58225/ch3all.htm#998335">SQL Functions</a></li><li><a href="http://www.pitt.edu/~hoffman/oradoc/server.804/a58225/ch3all.htm#1001608">User Functions</a></li><li><a href="http://www.pitt.edu/~hoffman/oradoc/server.804/a58225/ch3all.htm#1001660">Format Models</a></li><li><a href="http://www.pitt.edu/~hoffman/oradoc/server.804/a58225/ch3all.htm#1002628">Expressions</a></li><li><a href="http://www.pitt.edu/~hoffman/oradoc/server.804/a58225/ch3all.htm#1002893">Conditions</a></li></ul><p><strong>Note:</strong></p><ul><li>Functions, expressions, and descriptions preceded by</li><li>are available only if the Oracle objects option is installed on your database server.</li></ul><h3>Operators</h3><p>An operator manipulates individual data items and returns a result. The data items are called <em>operands</em> or <em>arguments</em>. Operators are represented by special characters or by keywords. For example, the multiplication operator is represented by an asterisk (*) and the operator that tests for nulls is represented by the keywords IS NULL. Tables in this section list SQL operators.</p><h3>Unary and Binary Operators</h3><p>There are two general classes of operators:</p><p>unary</p><p>A unary operator operates on only one operand. A unary operator typically appears with its operand in this format:</p><p>operator operand</p><p>binary</p><p>A binary operator operates on two operands. A binary operator appears with its operands in this format:</p><p>operand1 operator operand2</p><p>Other operators with special formats accept more than two operands. If an operator is given a null operand, the result is always null. The only operator that does not follow this rule is concatenation (||).</p><h3>Precedence</h3><p><em>Precedence</em> is the order in which Oracle evaluates different operators in the same expression. When evaluating an expression containing multiple operators, Oracle evaluates operators with higher precedence before evaluating those with lower precedence. Oracle evaluates operators with equal precedence from left to right within an expression.</p><p><a href="http://www.pitt.edu/~hoffman/oradoc/server.804/a58225/ch3all.htm#1003584">Table 3–1</a> lists the levels of precedence among SQL operators from high to low. Operators listed on the same line have the same precedence.</p><p><strong><em>Table 3–1 SQL Operator Precedence</em></strong>Operator Operation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*AIJSE_DGgvQfhNcFaOcNsw.png" /></figure><p>Example</p><p>In the following expression multiplication has a higher precedence than addition, so Oracle first multiplies 2 by 3 and then adds the result to 1.</p><pre>1+2*3</pre><p>You can use parentheses in an expression to override operator precedence. Oracle evaluates expressions inside parentheses before evaluating those outside.</p><p>SQL also supports set operators (UNION, UNION ALL, INTERSECT, and MINUS), which combine sets of rows returned by queries, rather than individual data items. All set operators have equal precedence.</p><h3>Arithmetic Operators</h3><p>You can use an arithmetic operator in an expression to negate, add, subtract, multiply, and divide numeric values. The result of the operation is also a numeric value. Some of these operators are also used in date arithmetic. <a href="http://www.pitt.edu/~hoffman/oradoc/server.804/a58225/ch3all.htm#997756">Table 3–2</a> lists arithmetic operators.</p><p><strong><em>Table 3–2 Arithmetic Operators</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*iMmdwXNxyRtOuaZBpGjWNg.png" /></figure><p>Do not use two consecutive minus signs with no separation ( — ) in arithmetic expressions to indicate double negation or the subtraction of a negative value. The characters — are used to begin comments within SQL statements. You should separate consecutive minus signs with a space or a parenthesis. For more information on comments within SQL statements, see <a href="http://www.pitt.edu/~hoffman/oradoc/server.804/a58225/ch2.htm#4320">“Comments”</a>.</p><h3>Concatenation Operator</h3><p>The concatenation operator manipulates character strings. <a href="http://www.pitt.edu/~hoffman/oradoc/server.804/a58225/ch3all.htm#997800">Table 3–3</a> describes the concatenation operator.</p><p><strong><em>Table 3–3 Concatenation Operator</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*HI-babVnK5oVInIUlfFCBA.png" /></figure><p>The result of concatenating two character strings is another character string. If both character strings are of datatype CHAR, the result has datatype CHAR and is limited to 2000 characters. If either string is of datatype VARCHAR2, the result has datatype VARCHAR2 and is limited to 4000 characters. Trailing blanks in character strings are preserved by concatenation, regardless of the strings’ datatypes. For more information on the differences between the CHAR and VARCHAR2 datatypes, see <a href="http://www.pitt.edu/~hoffman/oradoc/server.804/a58225/ch2.htm#3484">“Character Datatypes”</a>.</p><p>On most platforms, the concatenation operator is two solid vertical bars, as shown in <a href="http://www.pitt.edu/~hoffman/oradoc/server.804/a58225/ch3all.htm#997800">Table 3–3</a>. However, some IBM platforms use broken vertical bars for this operator. When moving SQL script files between systems having different character sets, such as between ASCII and EBCDIC, vertical bars might not be translated into the vertical bar required by the target Oracle environment. Oracle provides the CONCAT character function as an alternative to the vertical bar operator for cases when it is difficult or impossible to control translation performed by operating system or network utilities. Use this function in applications that will be moved between environments with differing character sets.</p><p>Although Oracle treats zero-length character strings as nulls, concatenating a zero-length character string with another operand always results in the other operand, so null can result only from the concatenation of two null strings. However, this may not continue to be true in future versions of Oracle. To concatenate an expression that might be null, use the NVL function to explicitly convert the expression to a zero-length string.</p><p>Example</p><p>This example creates a table with both CHAR and VARCHAR2 columns, inserts values both with and without trailing blanks, and then selects these values, concatenating them. Note that for both CHAR and VARCHAR2 columns, the trailing blanks are preserved.</p><pre>CREATE TABLE tab1 (col1 VARCHAR2(6), col2 CHAR(6),<br>        col3 VARCHAR2(6), col4 CHAR(6) );</pre><pre>Table created.</pre><pre>INSERT INTO tab1 (col1,  col2,     col3,     col4)<br>        VALUES   (&#39;abc&#39;, &#39;def   &#39;, &#39;ghi   &#39;, &#39;jkl&#39;);</pre><pre>1 row created.</pre><pre>SELECT col1||col2||col3||col4 &quot;Concatenation&quot;<br>        FROM tab1;</pre><pre>Concatenation<br>------------------------<br>abcdef   ghi   jkl</pre><h3>Comparison Operators</h3><p>Comparison operators compare one expression with another. The result of such a comparison can be TRUE, FALSE, or UNKNOWN. For information on conditions, see <a href="http://www.pitt.edu/~hoffman/oradoc/server.804/a58225/ch3all.htm#1002893">“Conditions”</a>. <a href="http://www.pitt.edu/~hoffman/oradoc/server.804/a58225/ch3all.htm#1016204">Table 3–4</a> lists comparison operators.</p><p><strong><em>Table 3–4 Comparison Operators</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*GqXthTzSuVCrwSPDaa5iiA.png" /></figure><p>Additional information on the NOT IN and LIKE operators appears in the sections that follow.</p><h4>NOT IN Operator</h4><p>If any item in the list following a NOT IN operation is null, all rows evaluate to UNKNOWN (and no rows are returned). For example, the following statement returns the string ‘TRUE’ for each row:</p><pre>SELECT &#39;TRUE&#39; <br>    FROM emp <br>    WHERE deptno NOT IN (5,15);</pre><p>However, the following statement returns no rows:</p><pre>SELECT &#39;TRUE&#39; <br>    FROM emp <br>    WHERE deptno NOT IN (5,15,null);</pre><p>The above example returns no rows because the WHERE clause condition evaluates to:</p><pre>deptno != 5 AND deptno != 15 AND deptno != null</pre><p>Because all conditions that compare a null result in a null, the entire expression results in a null. This behavior can easily be overlooked, especially when the NOT IN operator references a subquery.</p><h4>LIKE Operator</h4><p>The LIKE operator is used in character string comparisons with pattern matching. The syntax for a condition using the LIKE operator is shown in this diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/0*ZVJItp0JIze01q3l.gif" /></figure><p>where:</p><p><em>char1</em></p><p>is a value to be compared with a pattern. This value can have datatype CHAR or VARCHAR2.</p><p>NOT</p><p>logically inverts the result of the condition, returning FALSE if the condition evaluates to TRUE and TRUE if it evaluates to FALSE.</p><p><em>char2</em></p><p>is the pattern to which <em>char1</em> is compared. The pattern is a value of datatype CHAR or VARCHAR2 and can contain the special pattern matching characters % and _.</p><p>ESCAPE</p><p>identifies a single character as the escape character. The escape character can be used to cause Oracle to interpret % or _ literally, rather than as a special character, in the pattern.</p><p>If you wish to search for strings containing an escape character, you must specify this character twice. For example, if the escape character is ‘/’, to search for the string ‘client/server’, you must specify, ‘client//server’.</p><p>While the equal (=) operator exactly matches one character value to another, the LIKE operator matches a portion of one character value to another by searching the first value for the pattern specified by the second. Note that blank padding is <em>not</em> used for LIKE comparisons.</p><p>With the LIKE operator, you can compare a value to a pattern rather than to a constant. The pattern can only appear after the LIKE keyword. For example, you can issue the following query to find the salaries of all employees with names beginning with ‘SM’:</p><pre>SELECT sal <br>    FROM emp <br>    WHERE ename LIKE &#39;SM%&#39;;</pre><p>The following query uses the = operator, rather than the LIKE operator, to find the salaries of all employees with the name ‘SM%’:</p><pre>SELECT sal <br>    FROM emp <br>    WHERE ename = &#39;SM%&#39;;</pre><p>The following query finds the salaries of all employees with the name ‘SM%’. Oracle interprets ‘SM%’ as a text literal, rather than as a pattern, because it <em>precedes</em> the LIKE operator:</p><pre>SELECT sal <br>    FROM emp <br>    WHERE &#39;SM%&#39; LIKE ename;</pre><p>Patterns usually use special characters that Oracle matches with different characters in the value:</p><ul><li>An underscore (_) in the pattern matches exactly one character (as opposed to one byte in a multibyte character set) in the value.</li><li>A percent sign (%) in the pattern can match zero or more characters (as opposed to bytes in a multibyte character set) in the value. Note that the pattern ‘%’ cannot match a null.</li></ul><p>Case Sensitivity and Pattern Matching</p><p>Case is significant in all conditions comparing character expressions including the LIKE and equality (=) operators. You can use the UPPER() function to perform a case-insensitive match, as in this condition:</p><pre>UPPER(ename) LIKE &#39;SM%&#39;</pre><p><strong>Pattern Matching on Indexed Columns</strong></p><p>When LIKE is used to search an indexed column for a pattern, Oracle can use the index to improve the statement’s performance if the leading character in the pattern is not “%” or “_”. In this case, Oracle can scan the index by this leading character. If the first character in the pattern is “%” or “_”, the index cannot improve the query’s performance because Oracle cannot scan the index.</p><p>Example 1</p><p>This condition is true for all ENAME values beginning with “MA”:</p><pre>ename LIKE &#39;MA%&#39;</pre><p>All of these ENAME values make the condition TRUE:</p><pre>MARTIN, MA, MARK, MARY</pre><p>Case is significant, so ENAME values beginning with “Ma,” “ma,” and “mA” make the condition FALSE.</p><p>Example 2</p><p>Consider this condition:</p><pre>ename LIKE &#39;SMITH_&#39;</pre><p>This condition is true for these ENAME values:</p><pre>SMITHE, SMITHY, SMITHS</pre><p>This condition is false for ‘SMITH’, since the special character “_” must match exactly one character of the ENAME value.</p><p><strong>ESCAPE Option</strong></p><p>You can include the actual characters “%” or “_” in the pattern by using the ESCAPE option. The ESCAPE option identifies the escape character. If the escape character appears in the pattern before the character “%” or “_” then Oracle interprets this character literally in the pattern, rather than as a special pattern matching character.</p><p>Example:</p><p>To search for any employees with the pattern ‘A_B’ in their name:</p><pre>SELECT ename <br>    FROM emp <br>    WHERE ename LIKE &#39;%A\_B%&#39; ESCAPE &#39;\&#39;;</pre><p>The ESCAPE option identifies the backslash (\) as the escape character. In the pattern, the escape character precedes the underscore (_). This causes Oracle to interpret the underscore literally, rather than as a special pattern matching character.</p><p><strong>Patterns Without %</strong></p><p>If a pattern does not contain the “%” character, the condition can be TRUE only if both operands have the same length.</p><p>Example:</p><p>Consider the definition of this table and the values inserted into it:</p><pre>CREATE TABLE freds (f CHAR(6), v VARCHAR2(6));<br>INSERT INTO freds VALUES (&#39;FRED&#39;, &#39;FRED&#39;);</pre><p>Because Oracle blank-pads CHAR values, the value of F is blank-padded to 6 bytes. V is not blank-padded and has length 4.</p><h3>Logical Operators</h3><p>A logical operator combines the results of two component conditions to produce a single result based on them or to invert the result of a single condition. <a href="http://www.pitt.edu/~hoffman/oradoc/server.804/a58225/ch3all.htm#1010532">Table 3–5</a> lists logical operators.</p><p><strong><em>Table 3–5 Logical Operators</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*8XQtnghhcOCNjep8TEYRJw.png" /></figure><p>For example, in the WHERE clause of the following SELECT statement, the AND logical operator is used to ensure that only those hired before 1984 and earning more than $1000 a month are returned:</p><pre>SELECT * <br>    FROM emp <br>    WHERE hiredate &lt; TO_DATE(&#39;01-JAN-1984&#39;, &#39;DD-MON-YYYY&#39;) <br>        AND sal &gt; 1000;</pre><h4>NOT Operator</h4><p><a href="http://www.pitt.edu/~hoffman/oradoc/server.804/a58225/ch3all.htm#998106">Table 3–6</a> shows the result of applying the NOT operator to a condition.</p><p><strong><em>Table 3–6 NOT Truth Table</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36b076990e8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to JDBC Transaction w.r.t Spring Data JPA]]></title>
            <link>https://medium.com/@sendvjs/introduction-to-jdbc-transaction-w-r-t-spring-data-jpa-b41fdd139da6?source=rss-3ec6a97bfa28------2</link>
            <guid isPermaLink="false">https://medium.com/p/b41fdd139da6</guid>
            <dc:creator><![CDATA[Vikram]]></dc:creator>
            <pubDate>Sat, 10 Oct 2020 19:24:26 GMT</pubDate>
            <atom:updated>2020-10-10T19:24:26.512Z</atom:updated>
            <content:encoded><![CDATA[<ol><li><strong>Transaction</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*6rLrZ3hxd_onHj3Z_tdlhg.png" /></figure><p>The first thing that we need to know is what a transaction actually is. A series actions that are treated as a single unit of work is consider as transaction. Although there are multiple actions in a single transaction, all should either fail as a group or complete entirely as a group.</p><p>When a single action in the group fails, all actions should be rolled back. If all actions complete, then the transaction should be permanently committed. There are four key properties to transactions that can be easily remembered using the ACID acronym.</p><p>o Atomicity, a transaction consists of a series of actions, and the approach is an all-or-nothing approach. The transaction must either fully happen or not happen at all. It cannot partially complete.</p><p>o Consistency, a transaction is committed once all of its actions have completed. This keeps our data in a consistent state.</p><p>o Isolation, each transaction is isolated from other transactions to ensure that data is not corrupted. Isolation ensures that one transaction cannot read data from another transaction.</p><p>o Durability, a durable transaction is one that cannot be undone by system failure typically because it is written to persistent storage.</p><p><strong>2.</strong> <strong>Transaction Management</strong></p><p>Transaction management ensures data consistency and integrity. The ability to properly manage transactions is essential to enterprise application development because most enterprise apps almost always persists data to a database. Without transaction management, data could end-up in an consistent state and become corrupted.</p><p>To understand the importance of the transaction, think of a common example, buying a airline ticket online using a credit card.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*AyvA32rVHHFE9BNv4jKbKA.png" /></figure><p>In an online airline, ticket booking system, a booking may consists of two separate actions that together form a single transaction, paying for the seat and then reserving a seat and then reserving a seat, and removing it from inventory for the customer that just paid. Now think of the situation where the amount is charged to the credit card but a seat is never reserved nor confirmed for the passenger due to a system error. The data is left in an inconsistent state. The booking transaction should use transaction management so that both steps are performed as a single unit of work and all complete entirely as a group or fail as a group are rolled back.</p><pre><strong>try</strong> <strong>{<br></strong>conn <strong>=</strong> dataSource<strong>.</strong>getConnection<strong>();<br></strong>conn<strong>.</strong>setCommit<strong>(false);<br></strong>ticket<strong>.</strong>buy<strong>();<br></strong>seat<strong>.</strong>reseve<strong>();<br></strong>conn<strong>.</strong>commit<strong>();<br>}</strong> <strong>catch</strong> <strong>(SQLException</strong> e<strong>)</strong> <strong>{<br></strong>conn<strong>.</strong>rollback<strong>();<br>}</strong></pre><p>In this scenario, setting the correct boundaries for the transaction is important. When should a transaction start? When should a transaction end? When should the transaction be committed to the database? And when should data be rolled back in the case of exception?</p><p>Without transaction management, our data would be left in an inconsistent state. We are lucky that Spring provides transaction management support.</p><p>In a typical environment, there are two types of transactions, global and local.</p><p>o Global transactions are used when multiple resources manage the transactions and are typically managed by the application server, allowing for access to multiple resources like message queues, relational databases, …</p><p>o Local transactions are typically associated with a specific resource like a JDBC connection, and this resource manages the transaction. Local transactions do not typically run in a global environment.</p><h3>Using transaction with Spring</h3><p><strong>1.</strong> <strong>The advantages of the Spring framework</strong></p><p>Transaction management is a useful feature that the Spring framework makes available out of box. Spring provides support for automatically committing or rolling back transactions when they fail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*Vp1HCf-EGJMO2awsXApYQg.png" /></figure><p>There are several different APIs that help developer manage transactions.</p><p>o Java Transaction API</p><p>o Java Database Connectivity</p><p>o Hibernate</p><p>o Java Persistence API</p><p>o Java Data Objects</p><p>o Java Message Service</p><p>The advantages of using Spring to manage transactions is that it provides a consistent programming model across all of the APIs. For example, we are currently using JDO to help manage our transactions, and one day down the road we want to change to Hibernate. Well, if we are not using Spring, we’d have to make coding changes to support the migration because JDO and Hibernate have different APIs for transaction management.</p><p>If we’re using Spring, then coding changes aren’t required. Spring provides a uniform API that is simpler for programmatic transaction management than other complex APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*MUQE2Zj6HvtkQIYbOQMmjQ.png" /></figure><p>Let’s have a closer look at an example for this problem:</p><pre><strong>public</strong> <strong>void</strong> <strong>saveTicket(Ticket</strong> ticket<strong>)</strong> <strong>{<br>Session</strong> session <strong>=</strong> sessionFactory<strong>.</strong>getCurrentSession<strong>();<br></strong>session<strong>.</strong>getTransaction<strong>().</strong>begin<strong>();<br></strong>session<strong>.</strong>save<strong>(</strong>ticket<strong>);<br></strong>session<strong>.</strong>getTransaction<strong>().</strong>commit<strong>();<br>}</strong></pre><p>In the above code, we can find that we’re responsible for beginning the transaction, and commit the transaction. It is very manual. Then, we will see the code that’s using the Spring transaction management.</p><pre>@Transactional<br><strong>public</strong> <strong>void</strong> <strong>saveTicket(Ticket</strong> ticket<strong>)</strong> <strong>{<br></strong>sessionFactory<strong>.</strong>getCurrentSession<strong>().</strong>save<strong>(</strong>ticket<strong>);<br>}</strong></pre><p>Using the Spring transaction management, the piece of code is lightweight and flexible and lets Spring handle the transaction.</p><p>Let’s say we needed to execute <strong>saveTicket()</strong> as a part of complex transactions.</p><pre>@Transactional<br><strong>public</strong> <strong>void</strong> <strong>scheduleRelease(Ticket</strong> ticket<strong>,</strong> <strong>Release</strong> release<strong>)</strong> <strong>{<br></strong>ticketDao<strong>.</strong>saveTicket<strong>(</strong>ticket<strong>);<br></strong>assignToRelease<strong>(</strong>ticket<strong>);<br></strong>doOtherStuff<strong>(</strong>ticket<strong>);<br>}</strong></pre><p>In this example where we have to first save a ticket, assign it to a release, and do other stuff, the automatic rollback happens in the case of exception.</p><p>Spring makes all of this possible by providing support for programmatic and declarative transaction management. The above code of <strong>scheduleRelease()</strong> method is considered declarative transaction management. The underlying transaction manager should intercept resource manager requests made by the application and perform the necessary transaction management such as <strong>begin</strong>, <strong>suspend</strong>, <strong>commit</strong> and <strong>rollback</strong>. Declarative transaction management can also include <strong>the specification of transactional parameters</strong> such as <strong>isolation levels</strong>.</p><p>The advantages of declarative transactions:</p><p>o The declarative transactions allow container to manage the transaction for us.</p><p>o This saves us from having to put transaction management calls into our application code.</p><p>o Declarative transactional management can lead to much cleaner separation of business logic and transaction code. And application written to depend on declarative transaction management can be much easier to maintain and evolve.</p><p><strong>2.</strong> <strong>Programmatic transaction management</strong></p><p>In this section, we will see some tools for the programmatic transaction management.</p><p>o <strong>Transaction Template</strong>, is similar to Spring templates like JdbcTemplate and other available templates.</p><p>o <strong>Platform transaction manager</strong>, Spring makes available several implementations of the platform transaction manager interface for handling transactions across Hibernate, JDBC, JPA, JMS, etc such as Platform transaction manager, the Jta transaction manager, the Hibernate transaction manager, the DataSource transaction manager, and the JPA transaction manager, etc.</p><p>We will use Hibernate transaction manager because it’s a uniform API that uses the features of Hibernate’s transactions, while maintaining the advantage of Spring’s unified transaction abstractions.</p><p><strong>3.</strong> <strong>Declarative transaction management</strong></p><p>In the declarative transaction management, we usually use <strong>@Transactional</strong> annotation. It allows us to easily work with database transactions. The <strong>@Transactional</strong> annotation is convenient because developers don’t need to think about direct transaction management and exception handling.</p><p>o All of this is done automatically in a proxy class that Spring creates to hold the transaction management code.</p><p>o The <strong>@Transactional</strong> annotation can either be used at the class, interface, or method level. When placed on the class or interface, all methods within it become transactional.</p><p>o By using <strong>@Transactional</strong>, many important aspects such as transaction propagation are handled automatically. There are specific attributes that we can set that will determine propagation behavior.</p><p><strong>4.</strong> <strong>Spring boot and Transaction manager</strong></p><p>The <strong>@EnableTransactionManagement</strong> annotation enables Spring’s annotation-driven transaction management capability. However, when using Spring Boot, transaction management is automatically configured for us.</p><p>When looking at the sample code, we will see that the <strong>@Transactional</strong> annotation works without having to include the <strong>@EnableTransactionManagement</strong> annotation and declarative transaction management works, although we haven’t defined or configured a platform transaction manager.</p><p>The case study for the project uses Spring Boot, and we have added Spring Data JPA in our class path via pom.xml.</p><pre>&lt;dependency&gt;<br>&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>&lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Due to this dependency, Spring Boot does a lot for us behind the scenes.</p><p>o Spring registers a transaction manager for us, in this case a JPA transaction manager.</p><p>o It also takes care of the <strong>DataSource</strong>, <strong>EntityManager</strong>, repositories, etc. And calls on Spring Data repositories are by default surrounded by transaction.</p><p>o If Spring Data finds an existing transaction, the existing transaction will be reused. Otherwise, a new transaction is created.</p><p>Just remember when we’re not using Spring Boot, the <strong>@Transactional</strong> annotation within our code will be evaluated when we use the <strong>@EnableTransactionManagement</strong> annotation.</p><p>We can easily trace transaction behavior by adding the following property to our application.properties file.</p><pre>logging.level.org.springframework.transaction.interceptor=TRACE</pre><p>We can easily get access to the transaction manager by autowiring it with the following code.</p><pre>@Autowired<br><strong>private</strong> <strong>PlatformTransactionManager</strong> transactionManager<strong>;</strong></pre><p><strong>5.</strong> <strong>Entity Manager and Database transactions</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*y-73Qlia2ZIVBrxSS7Ae6g.png" /></figure><p>When we review the project code, we will see the use of an entity manager. So how does the entity manager fit in with the database transaction? In an ideal scenario, we will fully gain the benefit of Spring Data JPA, and remove the DAO completely and leave only the DAO interface.</p><p>Now, we will talk about persistence context and a database transaction. Each has its own lifecycle and scope.</p><p>o Database transaction</p><p>When the <strong>@Transactional</strong> annotation is used, it is only defining a single database transaction, in the scope of a persistence context.</p><p>o Persistence context</p><p>The persistence context comes from JPA, as does the entity manager, and is implemented internally using a Hibernate session when we’re using Hibernate as our persistence provider.</p><p>For example:</p><pre>@Entity<br><strong>public</strong> <strong>class</strong> <strong>Release</strong> <strong>{</strong></pre><pre>@Id<br>@GeneratedValue<strong>(</strong>strategy <strong>=</strong> <strong>GenerationType.</strong>AUTO<strong>)<br>private</strong> <strong>Integer</strong> id<strong>;<br>private</strong> <strong>String</strong> name<strong>;<br>private</strong> <strong>String</strong> description<strong>;</strong></pre><pre>@OneToMany<strong>(</strong>cascade <strong>=</strong> PERSIST<strong>)<br>private</strong> <strong>List&lt;Ticket&gt;</strong> tickets<strong>;</strong></pre><pre>@JsonFormat<strong>(</strong>shape <strong>=</strong> <strong>JsonFormat.</strong>Shape<strong>.</strong>STRING<strong>,</strong> pattern <strong>=</strong> &quot;yyyy-MM-dd&quot;<strong>)<br>private</strong> <strong>LocalDate</strong> releaseDate<strong>;</strong></pre><pre><strong>}<br></strong></pre><pre>@Repository<br><strong>public</strong> <strong>class</strong> <strong>ReleaseDAO</strong> <strong>implements</strong> <strong>IReleaseDAO</strong> <strong>{</strong></pre><pre>@PersistenceContext<br><strong>private</strong> <strong>EntityManager</strong> entityManager<strong>;</strong></pre><pre>@Override<br><strong>public</strong> <strong>void</strong> <strong>addRelease(Release</strong> release<strong>)</strong> <strong>{<br>this.</strong>entityManager<strong>.</strong>persist<strong>(</strong>release<strong>);<br>}</strong></pre><pre>@Override<br><strong>public</strong> <strong>Release</strong> <strong>getReleaseId(int</strong> releaseId<strong>)</strong> <strong>{<br>return</strong> <strong>this.</strong>entityManager<strong>.</strong>find<strong>(Release.</strong>class<strong>,</strong> releaseId<strong>);<br>}</strong></pre><pre><strong>}</strong></pre><p>The @Transactional annotation supports a set of attributes that you can use to customize the behavior. The most important ones are propagation, readOnly, rollbackFor, and noRollbackFor. Let’s take a closer look at each of them.</p><h3>Defining Transaction Propagation</h3><p>Spring’s Propagation enum defines 7 values that you can provide to the propagation attribute of the @Transactional annotation.</p><p>@Service<br>public class AuthorService {<br>private AuthorRepository authorRepository;<br>public AuthorService(AuthorRepository authorRepository) {<br>this.authorRepository = authorRepository;<br>}</p><p>@Transactional(propagation = Propagation.REQUIRES_NEW)<br>public void updateAuthorNameTransaction() {<br>Author author = authorRepository.findById(1L).get();<br>author.setName(&quot;new name&quot;);<br>}</p><p>}</p><p>They enable you to control the handling of existing and creation of new transactions. You can choose between:</p><p>REQUIRED to tell Spring to either join an active transaction or to start a new one if the method gets called without a transaction. This is the default behavior.</p><p>SUPPORTS to join an activate transaction if one exists. If the method gets called without an active transaction, this method will be executed without a transactional context.</p><p>· MANDATORY to join an activate transaction if one exists or to throw an Exception if the method gets called without an active transaction.</p><p>· NEVER to throw an Exception if the method gets called in the context of an active transaction.</p><p>· NOT_SUPPORTED to suspend an active transaction and to execute the method without any transactional context.</p><p>· REQUIRES_NEW to always start a new transaction for this method. If the method gets called with an active transaction, that transaction gets suspended until this method got executed.</p><p>· NESTED to start a new transaction if the method gets called without an active transaction. If it gets called with an active transaction, Spring sets a savepoint and rolls back to that savepoint if an Exception occurs.</p><h3>Using Read-Only Transactions</h3><p>Since Spring 5.1, this sets Hibernate’s <a href="https://thorben-janssen.com/11-jpa-hibernate-query-hints-every-developer-know/">query hint</a> org.hibernate.readOnly and avoids dirty checks on all retrieved entities.</p><p>@Service<br>public class AuthorService {<br>private AuthorRepository authorRepository;<br>public AuthorService(AuthorRepository authorRepository) {<br>this.authorRepository = authorRepository;<br>}</p><p>@Transactional(readOnly = true)<br>public Author getAuthor() {<br>return authorRepository.findById(1L).get();<br>}</p><p>}</p><h3>Handling Exceptions</h3><p>Spring proxy automatically rolls back your transaction if a RuntimeException or Error occurred. You can customize that behavior using the rollbackFor and noRollbackFor attributes of the @Transactional annotation.</p><p>As you might guess from its name, the rollbackFor attribute enables you to provide an array of Exception classes for which the transaction shall be rolled back. And the noRollbackFor attribute accepts an array of Exception classes that shall not cause a rollback of the transaction.</p><p>In the following example, I want to roll back the transaction for all subclasses of the Exception class except the EntityNotFoundException.</p><p>@Service<br>public class AuthorService {<br>private AuthorRepository authorRepository;<br>public AuthorService(AuthorRepository authorRepository) {<br>this.authorRepository = authorRepository;<br>}</p><p>@Transactional(rollbackFor = Exception.class,noRollbackFor = EntityNotFoundException.class)<br>public void updateAuthorName() {<br>Author author = authorRepository.findById(1L).get();<br>author.setName(&quot;new name&quot;);<br>}</p><p>}</p><h3>Conclusion</h3><p>Spring Boot and Spring Data JPA provide an easy to use transaction handling. You only need to annotate your interface, class, or method with Spring’s @Transactional annotation. Spring then wraps your service in a generated proxy that joins an active transaction or starts a new one and commits or rolls the transaction back after your method got executed.</p><p>You can customize the default behavior using the propagation, readOnly, rollbackFor, and noRollbackFor attributes:</p><p>· The propagation attribute gives you control over the handling of existing and the creation of new transactions. If your method gets called within the context of an activate transaction, you can, for example, decide if your method shall join that transaction, create a new one, or fail.</p><p>· You can use the readOnly attribute to improve the performance of read-only operations.</p><p>· The rollbackFor and noRollbackFor attributes enable you to define which Exception classes will cause a rollback of your transaction and which can be handled by your business logic.</p><h3>Benefits</h3><p>The Spring framework allows transactions to be managed seamlessly by offering a consistent programming model across global and local transactions. Essentially code is written once benefitting from different transaction management strategies within different environment.</p><p>Spring provides supports for programmatic transaction management. Now this is where the developer writes custom code to manage the transaction and set boundaries. Spring also provides support for declarative transaction management, which allows developers to separate transaction management from the business code.</p><p>Spring supports isolation levels that help developers avoid problems that may arise when multiple transactions in the application are operating concurrently on the same data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b41fdd139da6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connect From Your Local Machine to a PostgreSQL Database in Docker]]></title>
            <link>https://medium.com/@sendvjs/connect-from-your-local-machine-to-a-postgresql-database-in-docker-c1e54ec5c10a?source=rss-3ec6a97bfa28------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1e54ec5c10a</guid>
            <category><![CDATA[docker-postgres]]></category>
            <dc:creator><![CDATA[Vikram]]></dc:creator>
            <pubDate>Sat, 27 Jun 2020 07:14:04 GMT</pubDate>
            <atom:updated>2020-06-27T07:14:04.128Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/849/0*f0-4k7T_wV1LBqmv.png" /></figure><p>Docker makes it very easy to spin up a PostgreSQL database management system. With the following command it is possible to start your PostgreSQL Docker container on your server or local machine:</p><pre>$ docker run -d -p 5432:5432 --name my-postgres -e POSTGRES_PASSWORD=mysecretpassword postgres</pre><p>This command will start a PostgreSQL database and map ports using the following pattern: -p &lt;host_port&gt;:&lt;container_port&gt;.<br>Port 5432 of our container will be mapped on port 5432 of our host or server.</p><p>Access the container on your host or server. We will create a database inside our PostgreSQL container.</p><pre>$ docker exec -it my-postgres bash</pre><p>Now you are ‘inside’ your container. We can access postgres and create the database.</p><pre>root@cb9222b1f718:/# psql -U postgres<br>psql (10.3 (Debian 10.3-1.pgdg90+1))<br>Type &quot;help&quot; for help.postgres=# CREATE DATABASE mytestdb;<br>CREATE DATABASE<br>postgres=#\q</pre><p>We are finished. You can exit your container (\q) and go to your local machine. Here you need some PostgreSQL Client tool installed:</p><ul><li>PSQL (CLI)</li><li>PgAdmin</li></ul><p>My PostgreSQL container is running on my local machine, which explains why I am connecting with localhost. If it is running on a specific server, use your server IP. (For Windows docker-machine you probably need to use 192.168.99.100).</p><pre>$ psql -h localhost -p 5432 -U postgres -W                       Password for user postgres:                       <br>psql (9.5.5, server 10.3 (Debian 10.3-1.pgdg90+1))                       WARNING: psql major version 9.5, server major version 10.                                Some psql features might not work.                       <br>Type &quot;help&quot; for help.                                               postgres=# \l<br>                                 List of databases<br>   Name    |  Owner   | Encoding |  Collate   |   Ctype    |  <br>-----------+----------+----------+------------+------------+<br> mytestdb  | postgres | UTF8     | en_US.utf8 | en_US.utf8 |<br> postgres  | postgres | UTF8     | en_US.utf8 | en_US.utf8 |<br> template0 | postgres | UTF8     | en_US.utf8 | en_US.utf8 |<br>           |          |          |            |            |<br> template1 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | <br>           |          |          |            |            | <br>(4 rows)</pre><p>After authenticating you will see the mytestdb is in the list of available databases. Now you can connect with your database using \c .</p><p>For a tool like PgAdmin you can define your connection. Also, here you have to replace localhost with your server IP if your container is running elsewhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wgoaraZIM87_F5-g.png" /></figure><p>Create a server connection</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TaprDv4kvWhMgJwl.png" /></figure><p>Define your connection</p><p>Save the connection and you can connect to the database which is running in your PostgreSQL Docker container!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1e54ec5c10a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot — Caching]]></title>
            <link>https://medium.com/@sendvjs/spring-boot-caching-4ceeac1c9f36?source=rss-3ec6a97bfa28------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ceeac1c9f36</guid>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Vikram]]></dc:creator>
            <pubDate>Sat, 20 Jun 2020 08:55:19 GMT</pubDate>
            <atom:updated>2020-06-20T08:55:19.825Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Boot — Caching</h3><p>This topic will give you understanding of usage Spring Boot with Caching to increase your app performance significantly 🚀 !</p><p>Every one of you faces or has faced with the problem of <strong><em>slow service.</em></strong></p><p>Well, there are lots of reasons why your service could work not as fast as you’d expect it to work. Among popular ones:</p><ul><li>High load — when your service faces big pressure from users;</li><li>Complicated Business Logic — when there are lots of stuff that needs to be computed, calculated during each user request.</li><li>Remote Database — it’s a good practice to have your database hosted by some well-trusted provider, and to be sure it is secured and backed up on a regular basis. But also it impacts the performance, since it requires more time to go from server to the remote database and back with needed data.</li></ul><p>So as you see, reasons of slowness might be multitudinous.</p><h3>The solution for this is : Caching</h3><p>Spring Framework has a really powerful tool to improve your server performance and availability. This is : <strong><em>Spring Cache!</em></strong></p><p>So let’s take a closer look at caching data by creating step-by-step server application with <strong>Spring Boot </strong>using<strong> Spring Cache</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P3mjtIRgvSNEBula.png" /></figure><p>Probably the fastest way to create spring boot project is by generating it from <a href="https://start.spring.io/"><em>Spring Initialzr</em></a><em>. </em>Dependencies that we need are: Web and Cache for now. So download it, unzip and open with you favorite IDE. I prefer IntelliJIdea.</p><p>So, when you open it you’ll have the next project structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sYBVdRa6fnWDyGZ-.png" /></figure><p>Okay, next we’ll create <strong>User </strong>domain class + <strong>UserService </strong>that will fill out dummy data for users + <strong>UserController </strong>that will define our endpoints.</p><p>Our User.class will look like this:</p><pre>@Data<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@Builder<br>public class User {</pre><pre>    private String username;<br>    private int age;<br>}</pre><p>Please note annotations above the class name. All they are from <strong>lombok </strong>library, that you can add to your project using Maven dependency:</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>   &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>   &lt;version&gt;1.16.16&lt;/version&gt;<br>   &lt;scope&gt;provided&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>UserController for now will have only one mapping — to fetch all users:</p><pre>@RestController<br><strong>@RequestMapping(value = &quot;/users&quot;)</strong><br>public class UserController {</pre><pre>    private final UserService userService;</pre><pre>    @Autowired<br>    UserController (UserService userService) {<br>        this.userService = userService;<br>    }</pre><pre>    <strong>@GetMapping(value = &quot;/all&quot;)</strong><br>    public List&lt;User&gt; getAllUsers() {<br>        return <em>userService.findAll()</em>;<br>    }<br>}</pre><p>And UserService, where all magic will take place, for now looks like following:</p><pre>@Service<br>public class UserService {</pre><pre>    private List&lt;User&gt; users = new ArrayList&lt;&gt;();</pre><pre>    @Autowired<br>    UserService() {}</pre><pre>    @PostConstruct<br>    private void fillUsers() {<br>       users.add(User.<em>builder</em>().username(&quot;user_1&quot;).age(20).build());<br>       users.add(User.<em>builder</em>().username(&quot;user_2&quot;).age(76).build());<br>       users.add(User.<em>builder</em>().username(&quot;user_3&quot;).age(54).build());<br>       users.add(User.<em>builder</em>().username(&quot;user_4&quot;).age(30).build());<br>    }</pre><pre>    public List&lt;User&gt; findAll() {<br>        <strong><em>simulateSlowService();</em></strong><br>        return this.users;<br>    }</pre><pre>    <strong><em>private void simulateSlowService() {<br>        try {<br>            Thread.sleep(3000L);<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br>    }</em></strong><br>}</pre><p>So, as you see, we have only one endpoint for now — <a href="http://localhost:8080/users/all">http://localhost:8080/users/all</a> — that should return all users, stored in variable <strong><em>users</em></strong>.</p><p>But we are simulating that our service is really slow, by calling method <strong><em>simulateSlowService()</em></strong> — that will just wait 3 seconds before executing logic inside the <strong><em>findAll()</em></strong> method.</p><p>And when you execute GET request to our find all users endpoint, you’ll get next result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tpG3zgWqAVXMbbNM.png" /></figure><p>So, it takes about 3227 milliseconds to get all users. And this is an horrible scenario for real use case 😏</p><p>So here <strong><em>Spring Cache</em></strong> can solve our issue!</p><p>Let’s change the code!</p><p>Main SpringBootWithCachingApplication.class</p><pre>@SpringBootApplication<br><strong><em>@EnableCaching //enables Spring Caching functionality</em></strong><br>public class SpringBootWithCachingApplication {</pre><pre>   public static void main(String[] args) {<br>      SpringApplication.<em>run</em>(SpringBootWithCachingApplication.class, args);<br>   }<br>}</pre><p>And UserService.class</p><pre>@Service<br><strong><em>@CacheConfig(cacheNames={&quot;users&quot;}) // </em></strong><em>tells Spring where to store cache for this class</em><br>public class UserService {</pre><pre>    private List&lt;User&gt; users = new ArrayList&lt;&gt;();</pre><pre>    @Autowired<br>    UserService() {}</pre><pre>    @PostConstruct<br>    private void fillUsers() {<br>       users.add(User.<em>builder</em>().username(&quot;user_1&quot;).age(20).build());<br>       users.add(User.<em>builder</em>().username(&quot;user_2&quot;).age(76).build());<br>       users.add(User.<em>builder</em>().username(&quot;user_3&quot;).age(54).build());<br>       users.add(User.<em>builder</em>().username(&quot;user_4&quot;).age(30).build());<br>    }</pre><pre>    <strong><em>@Cacheable // </em></strong>caches the result of findAll() method<br>    public List&lt;User&gt; findAll() {<br>        simulateSlowService();<br>        return this.users;<br>    }</pre><pre>    private void simulateSlowService() {<br>        try {<br>            Thread.<em>sleep</em>(3000L);<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><p><strong><em>@CacheConfig</em></strong> — you can define some of the cache configuration in one place — at the class level — so that you won’t need to declare stuff several times.</p><p><strong><em>@Cacheable</em></strong> — when method annotated with this annotation, it will be executed only once for the given cachekey, until the cache expires or gets cleared.</p><p>So, now when you restarted the server and make GET request to fetch all users — first time it will take those 3 with something seconds to get data back to you. Because firstly it will check the cache, and will see that it is empty, and will execute the method, with 3 seconds delay. But all further requests to findAll() will be executed much much faster, because method will not be executed, since requested data was cached previously and will be taken for you from the cache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3BI6OKy-q1UPm139.png" /></figure><p>As you see, the request execution time is much less, than before. It’s simply because the method findAll() is not executed, since the data is already in cache, that’s why it works so fast</p><p>Alright! This is good. But not enough. Imagine that some user got update, for example username of first user changed from “user_1” to “user_super_1”. And since method findAll() marked as cacheable, it won’t be executed, and we will get back old data from cache all the time. And this is definitely not something that we want.</p><p>So basically, whenever something changes(update, save requests) — we need to properly update our cache. Let’s see how that is possible.</p><p>For instance, I’ll add some method that will change first user in array.</p><pre>@CachePut<br>public User updateUser(User user) {<br>    this.users.set(0, user);<br>    return this.users.get(0);<br>}</pre><p><strong><em>@CachePut</em></strong> — always lets the method execute. It is used to update the cache with the result of the method execution</p><p>So, when we update the first user, and the appropriate method annotated with @CachePut annotation — it will update the cache itself, and the request to findAll() will return us recently updated data. Again, it will be executed very and very fast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qh8aMjMwgTndQUpN.png" /></figure><p>And also there is one more interesting part left:</p><p><strong><em>@CacheEvict</em></strong> — removes data from from the cache. You can use in different ways:</p><ul><li>if you want to flush all the cache</li></ul><pre>@CacheEvict(allEntries = true)</pre><ul><li>Or remove item by key</li></ul><pre>@CacheEvict(key = &quot;#user.username&quot;)</pre><p>This way you won’t keep data in the cache, that you won’t need to use anymore.</p><p>This is basically how Spring Cache can help you in solving performance issue during you development process. But keep in mind not to use caching where it’s not needed. Be wise!</p><p>Source Code : <a href="https://github.com/vikramjitsaha/poc/blob/master/spring-boot-with-caching-master.zip">https://github.com/vikramjitsaha/poc/blob/master/spring-boot-with-caching-master.zip</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ceeac1c9f36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Rest API — Security]]></title>
            <link>https://medium.com/@sendvjs/spring-rest-api-security-2cd9f52381a6?source=rss-3ec6a97bfa28------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cd9f52381a6</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Vikram]]></dc:creator>
            <pubDate>Thu, 18 Jun 2020 10:52:21 GMT</pubDate>
            <atom:updated>2020-06-18T10:52:21.281Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Rest API — Security</h3><h3>Using — JSON Web Token</h3><p>In this piece, I am going to walk you through how to secure a Spring Boot REST API with JSON Web Token (JWT) to exchange claims between a server and a client. Here I will be demonstrating how to secure an Angular 2+ application using Spring Boot as a RESTful back end. You can find the Angular integration project at : <a href="https://github.com/vikramjitsaha/poc/blob/master/angular-springboot-jwt-master.zip">https://github.com/vikramjitsaha/poc/blob/master/angular-springboot-jwt-master.zip</a></p><h3>Introduction</h3><p>Over the past few years, Spring Boot has greatly simplified the configuration of Spring Framework applications. The unceremonious approach it takes lets developers enable basic security for an application by simply having Spring Security dependency on the classpath.</p><p>Choosing JWT to secure your API endpoints is a great choice because it ensures a stateless exchange of tokens between the client and the server, and is compact and URL-safe. With JWT, it is not necessary to store access tokens in a database (although you may still do that and even need to depending on the use case) or worry about sticky sessions. This makes building redundancy into your enterprise application more cost-effective, at least as far as the security aspect is concerned. You do, however, need to deal with other aspects such as token revocation, but that is not covered here. The basis for understanding how useful JWT is is to first grasp OAuth 2.0. For a quick reference, below is an illustration of the OAuth dance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/0*VOvkdjpQekmOF6t0.png" /></figure><h3>What you will need for the project?</h3><p>1. Spring Boot 1.5.3.RELEASE project with either Maven or Gradle. This project uses Maven.</p><p>2. The following dependencies:</p><ul><li>spring-boot-starter-web</li><li>spring-boot-starter-security</li><li>spring-boot-starter-data-jpa</li><li>spring-boot-starter-web</li><li>com.h2database — H2 Database for storing sample test data</li><li>spring-security-jwt version: 1.0.7.RELEASE</li><li>spring-security-oauth2 version: 2.1.0.RELEASE</li></ul><h3>Final project structure</h3><p>When you clone the project from Github and import it into your IDE, for instance, its structure will look similar to the following. Here, I am using a screenshot from IntelliJ Community Edition IDE. Yours will look slightly different depending on the IDE you use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/0*F7AfvVMNju3tHJ5k.png" /></figure><h3>1. Configure Spring Security</h3><p>Thanks to Spring Boot’s autoconfiguration we will need minimal customizations to get set:</p><p>First, let’s look at the application’s configuration file, application.properties:</p><pre>security.oauth2.resource.filter-order=3<br><br>security.signing-key=MaYzkSjmkzPC57L<br>security.encoding-strength=256<br>security.security-realm=Spring Boot JWT Example Realm<br><br>security.jwt.client-id=testjwtclientid<br>security.jwt.client-secret=XY7kmzoNzl100<br>security.jwt.grant-type=password<br>security.jwt.scope-read=read<br>security.jwt.scope-write=write<br>security.jwt.resource-ids=testjwtresourceid</pre><p>Then the security configuration class:</p><pre>@Configuration<br>@EnableWebSecurity<br>@EnableGlobalMethodSecurity(prePostEnabled = true)<br>public class SecurityConfig extends WebSecurityConfigurerAdapter {<br><br>   @Value(&quot;${security.signing-key}&quot;)<br>   private String signingKey;<br><br>   @Value(&quot;${security.encoding-strength}&quot;)<br>   private Integer encodingStrength;<br><br>   @Value(&quot;${security.security-realm}&quot;)<br>   private String securityRealm;<br><br>   @Autowired<br>   private UserDetailsService userDetailsService;<br><br>   @Bean<br>   @Override<br>   protected AuthenticationManager authenticationManager() throws Exception {<br>      return super.authenticationManager();<br>   }<br><br>   @Override<br>   protected void configure(AuthenticationManagerBuilder auth) throws Exception {<br>      auth.userDetailsService(userDetailsService)<br>              .passwordEncoder(new ShaPasswordEncoder(encodingStrength));<br>   }<br><br>   @Override<br>   protected void configure(HttpSecurity http) throws Exception {<br>      http<br>              .sessionManagement()<br>              .sessionCreationPolicy(SessionCreationPolicy.STATELESS)<br>              .and()<br>              .httpBasic()<br>              .realmName(securityRealm)<br>              .and()<br>              .csrf()<br>              .disable();<br><br>   }<br><br>   @Bean<br>   public JwtAccessTokenConverter accessTokenConverter() {<br>      JwtAccessTokenConverter converter = new JwtAccessTokenConverter();<br>      converter.setSigningKey(signingKey);<br>      return converter;<br>   }<br><br>   @Bean<br>   public TokenStore tokenStore() {<br>      return new JwtTokenStore(accessTokenConverter());<br>   }<br><br>   @Bean<br>   @Primary //Making this primary to avoid any accidental duplication with another token service instance of the same name<br>   public DefaultTokenServices tokenServices() {<br>      DefaultTokenServices defaultTokenServices = new DefaultTokenServices();<br>      defaultTokenServices.setTokenStore(tokenStore());<br>      defaultTokenServices.setSupportRefreshToken(true);<br>      return defaultTokenServices;<br>   }<br>}</pre><ul><li>@EnableWebSecurity: Enables spring security and tells Spring Boot to apply all the sensitive defaults</li><li>@EnableGlobalMethodSecurity: Allows us to have method level access control</li><li>JwtTokenStore and JwtAccessTokenConverter beans: A JwtTokenStore bean is needed by the authorization server and to enable the resource server to decode access tokens a JwtAccessTokenConverter bean must be used by both servers. In this case, we are providing a symmetric key signing.</li><li>UserDetailsService: We inject a custom implementation of UserDetailsService, named AppUserDetailsService (see the code on GitHub for details) in order to retrieve user details from the database.</li><li>Encoding: SHA-256 is used to encode passwords. This is set in encodingStrength property</li><li>Realm: The security realm name is defined in securityRealm property. This name is arbitrary. A realm is basically all that define our security solution from the provider to roles, users, etc.</li></ul><h3>2. Configure Authorization Server</h3><pre>@Configuration<br>@EnableAuthorizationServer<br>public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {<br><br>   @Value(&quot;${security.jwt.client-id}&quot;)<br>   private String clientId;<br><br>   @Value(&quot;${security.jwt.client-secret}&quot;)<br>   private String clientSecret;<br><br>   @Value(&quot;${security.jwt.grant-type}&quot;)<br>   private String grantType;<br><br>   @Value(&quot;${security.jwt.scope-read}&quot;)<br>   private String scopeRead;<br><br>   @Value(&quot;${security.jwt.scope-write}&quot;)<br>   private String scopeWrite = &quot;write&quot;;<br><br>   @Value(&quot;${security.jwt.resource-ids}&quot;)<br>   private String resourceIds;<br><br>   @Autowired<br>   private TokenStore tokenStore;<br><br>   @Autowired<br>   private JwtAccessTokenConverter accessTokenConverter;<br><br>   @Autowired<br>   private AuthenticationManager authenticationManager;<br><br>   @Override<br>   public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {<br>      configurer<br>              .inMemory()<br>              .withClient(clientId)<br>              .secret(clientSecret)<br>              .authorizedGrantTypes(grantType)<br>              .scopes(scopeRead, scopeWrite)<br>              .resourceIds(resourceIds);<br>   }<br><br>   @Override<br>   public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {<br>      TokenEnhancerChain enhancerChain = new TokenEnhancerChain();<br>      enhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));<br>      endpoints.tokenStore(tokenStore)<br>              .accessTokenConverter(accessTokenConverter)<br>              .tokenEnhancer(enhancerChain)<br>              .authenticationManager(authenticationManager);<br>   }<br><br>}</pre><ul><li>@EnableAuthorizationServer: Enables an authorization server</li><li>AuthorizationServerConfig which is our authorization server configuration class extends AuthorizationServerConfigurerAdapter which in turn is an implementation of AuthorizationServerConfigurer. The presence of a bean of type AuthorizationServerConfigurer simply tells Spring Boot to switch off auto-configuration and use the custom configuration. Also, the AuthorizationServerConfig, like any other configuration class, has its definition automatically scanned, wired, and applied by Spring Boot because of the @Configuration annotation.</li><li>Client id: defines the id of the client application that is authorized to authenticate, the client application provides this in order to be allowed to send a request to the server.</li><li>Client secret: is the client application’s password. In a non-trivial implementation client ids and passwords will be securely stored in a database and retrievable through a separate API that clients applications access during deployment. These pieces of information can also be shared and stored in environment variables although that would not be my preferred option.</li><li>Grant type: we define the grant type password here because it’s not enabled by default</li><li>The scope: read/write defines the level of access we are allowing to resources</li><li>Resource Id: The resource id specified here must be specified on the resource server as well</li><li>AuthenticationManager: Spring’s authentication manager takes care of checking user credential validity</li><li>TokenEnhancerChain: We define a token enhancer that enables chaining multiple types of claims containing different information</li></ul><h3>3. Configure the Resource Server</h3><pre>@Configuration<br>@EnableResourceServer<br>public class ResourceServerConfig extends ResourceServerConfigurerAdapter {<br>    @Autowired<br>    private ResourceServerTokenServices tokenServices;<br><br>    @Value(&quot;${security.jwt.resource-ids}&quot;)<br>    private String resourceIds;<br><br>    @Override<br>    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {<br>        resources.resourceId(resourceIds).tokenServices(tokenServices);<br>    }<br><br>    @Override<br>    public void configure(HttpSecurity http) throws Exception {<br>                http<br>                .requestMatchers()<br>                .and()<br>                .authorizeRequests()<br>                .antMatchers(&quot;/actuator/**&quot;, &quot;/api-docs/**&quot;).permitAll()<br>                .antMatchers(&quot;/springjwt/**&quot; ).authenticated();<br>    }<br>}</pre><p><a href="http://twitter.com/EnableResourceServer">@EnableResourceServer</a>: Enables a resource server. By default, this annotation creates a security filter which authenticates requests via an incoming OAuth2 token. The filter is an instance of WebSecurityConfigurerAdapter which has an hard-coded order of three (Due to some limitations of Spring Framework). You need to tell Spring Boot to set the OAuth2 request filter order to three to align with the hardcoded value. You do that by adding security.oauth2.resource.filter-order = 3 in the application.properties file. Hopefully, this will be fixed in future releases.</p><p>The resource server has the authority to define the permission for any endpoint. The endpoint permission is defined with:<br>.antMatchers(“/actuator/**”, “/api-docs/**”).permitAll()<br>.antMatchers(“/springjwt/**”).authenticated()</p><p>Notice here that the resource and the authorization servers both use the same token service. That is because they are in the same code base so we are reusing the same bean.</p><h3>4. Configure a Data Source</h3><pre>@Configuration<br>@EnableTransactionManagement<br>@EnableJpaRepositories(basePackages = &quot;com.nouhoun.springboot.jwt.integration.repository&quot;)<br>public class DatasourceConfig {<br><br>    @Bean<br>    public DataSource datasource() throws PropertyVetoException {<br>        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();<br>        EmbeddedDatabase dataSource = builder<br>                .setType(EmbeddedDatabaseType.H2)<br>                .addScript(&quot;sql-scripts/schema.sql&quot;)<br>                .addScript(&quot;sql-scripts/data.sql&quot;)<br>                .build();<br><br>        return dataSource;<br>    }<br><br>    @Bean<br>    public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Qualifier(&quot;datasource&quot;) DataSource ds) throws PropertyVetoException{<br>        LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();<br>        entityManagerFactory.setDataSource(ds);<br>        entityManagerFactory.setPackagesToScan(new String[]{&quot;com.nouhoun.springboot.jwt.integration.domain&quot;});<br>        JpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();<br>        entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter);<br>        return entityManagerFactory;<br>    }<br><br>    @Bean<br>    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory){<br>        JpaTransactionManager transactionManager = new JpaTransactionManager();<br>        transactionManager.setEntityManagerFactory(entityManagerFactory);<br>        return transactionManager;<br>    }<br>}</pre><p>Spring Boot can fully auto-configure the in-memory H2 data source once it’s defined on the classpath. However, to give you a better sense of how you can take control of your application and customize your data source the following configuration is provided:</p><p>Replace H2 with any database (MariaDB, MySQL, Oracle, SQL Server, etc.) to fit your use case.</p><h3>5. Database Scripts and Test Data</h3><h3>schema.sql</h3><pre>CREATE TABLE random_city (<br>  id bigint(20) NOT NULL AUTO_INCREMENT,<br>  name varchar(255) DEFAULT NULL,<br>  PRIMARY KEY (id)<br>);<br><br>CREATE TABLE app_role (<br>  id bigint(20) NOT NULL AUTO_INCREMENT,<br>  description varchar(255) DEFAULT NULL,<br>  role_name varchar(255) DEFAULT NULL,<br>  PRIMARY KEY (id)<br>);<br><br><br>CREATE TABLE app_user (<br>  id bigint(20) NOT NULL AUTO_INCREMENT,<br>  first_name varchar(255) NOT NULL,<br>  last_name varchar(255) NOT NULL,<br>  password varchar(255) NOT NULL,<br>  username varchar(255) NOT NULL,<br>  PRIMARY KEY (id)<br>);<br><br><br>CREATE TABLE user_role (<br>  user_id bigint(20) NOT NULL,<br>  role_id bigint(20) NOT NULL,<br>  CONSTRAINT FK859n2jvi8ivhui0rl0esws6o FOREIGN KEY (user_id) REFERENCES app_user (id),<br>  CONSTRAINT FKa68196081fvovjhkek5m97n3y FOREIGN KEY (role_id) REFERENCES app_role (id)<br>);</pre><h3>data.sql</h3><pre>INSERT INTO app_role (id, role_name, description) VALUES (1, &#39;STANDARD_USER&#39;, &#39;Standard User - Has no admin rights&#39;);<br>INSERT INTO app_role (id, role_name, description) VALUES (2, &#39;ADMIN_USER&#39;, &#39;Admin User - Has permission to perform admin tasks&#39;);<br><br>-- USER<br>-- non-encrypted password: jwtpass<br>INSERT INTO app_user (id, first_name, last_name, password, username) VALUES (1, &#39;John&#39;, &#39;Doe&#39;, &#39;821f498d827d4edad2ed0960408a98edceb661d9f34287ceda2962417881231a&#39;, &#39;john.doe&#39;);<br>INSERT INTO app_user (id, first_name, last_name, password, username) VALUES (2, &#39;Admin&#39;, &#39;Admin&#39;, &#39;821f498d827d4edad2ed0960408a98edceb661d9f34287ceda2962417881231a&#39;, &#39;admin.admin&#39;);<br><br><br>INSERT INTO user_role(user_id, role_id) VALUES(1,1);<br>INSERT INTO user_role(user_id, role_id) VALUES(2,1);<br>INSERT INTO user_role(user_id, role_id) VALUES(2,2);<br><br>-- Populate random city table<br><br>INSERT INTO random_city(id, name) VALUES (1, &#39;Bamako&#39;);<br>INSERT INTO random_city(id, name) VALUES (2, &#39;Nonkon&#39;);<br>INSERT INTO random_city(id, name) VALUES (3, &#39;Houston&#39;);<br>INSERT INTO random_city(id, name) VALUES (4, &#39;Toronto&#39;);<br>INSERT INTO random_city(id, name) VALUES (5, &#39;New York&#39;);<br>INSERT INTO random_city(id, name) VALUES (6, &#39;Mopti&#39;);<br>INSERT INTO random_city(id, name) VALUES (7, &#39;Koulikoro&#39;);<br>INSERT INTO random_city(id, name) VALUES (8, &#39;Moscow&#39;);</pre><h3>6. Entities</h3><p>User, Role, RandomCity entities are created to map to the data model</p><h3>7. Exposing Resources via a REST Controller</h3><pre>@RestController<br>@RequestMapping(&quot;/springjwt&quot;)<br>public class ResourceController {<br>    @Autowired<br>    private GenericService userService;<br><br>    @RequestMapping(value =&quot;/cities&quot;)<br>    @PreAuthorize(&quot;hasAuthority(&#39;ADMIN_USER&#39;) or hasAuthority(&#39;STANDARD_USER&#39;)&quot;)<br>    public List&lt;RandomCity&gt; getUser(){<br>        return userService.findAllRandomCities();<br>    }<br><br>    @RequestMapping(value =&quot;/users&quot;, method = RequestMethod.GET)<br>    @PreAuthorize(&quot;hasAuthority(&#39;ADMIN_USER&#39;)&quot;)<br>    public List&lt;User&gt; getUsers(){<br>        return userService.findAllUsers();<br>    }<br>}</pre><p>Here two endpoints are exposed</p><ul><li>/springjwt/cities: This endpoint is accessible to all authenticated users</li><li>/springjwt/users: This endpoint is accessible only to an admin user</li></ul><h3>8. Running and Testing the Application</h3><p>First, you will need the following basic pieces of information:</p><ul><li>client: testjwtclientid</li><li>secret: XY7kmzoNzl100</li><li>Non-admin username and password: john.doe and jwtpass</li><li>Admin user: admin.admin and jwtpass</li><li>Example of resource accessible to all authenticated users: <a href="http://localhost:8080/springjwt/cities">http://localhost:8080/springjwt/cities</a></li><li>Example of resource accessible to only an admin user: <a href="http://localhost:8080/springjwt/users">http://localhost:8080/springjwt/users</a></li></ul><h3>Step 1: Generate an access token</h3><p>Use the following generic command to generate an access token: $ curl client:secret@localhost:8080/oauth/token -d grant_type=password -d username=user -d password=pwd</p><p>For this specific application, to generate an access token for the non-admin user john.doe, run: $ curl testjwtclientid:XY7kmzoNzl100@localhost:8080/oauth/token -d grant_type=password -d username=john.doe -d password=jwtpass. You&#39;ll receive a response similar to below:</p><pre>`<br>{<br>  &quot;access_token&quot;: &quot;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsidGVzdGp3dHJlc291cmNlaWQiXSwidXNlcl9uYW1lIjoiYWRtaW4uYWRtaW4iLCJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoxNDk0NDU0MjgyLCJhdXRob3JpdGllcyI6WyJTVEFOREFSRF9VU0VSIiwiQURNSU5fVVNFUiJdLCJqdGkiOiIwYmQ4ZTQ1MC03ZjVjLTQ5ZjMtOTFmMC01Nzc1YjdiY2MwMGYiLCJjbGllbnRfaWQiOiJ0ZXN0and0Y2xpZW50aWQifQ.rvEAa4dIz8hT8uxzfjkEJKG982Ree5PdUW17KtFyeec&quot;,<br>  &quot;token_type&quot;: &quot;bearer&quot;,<br>  &quot;expires_in&quot;: 43199,<br>  &quot;scope&quot;: &quot;read write&quot;,<br>  &quot;jti&quot;: &quot;0bd8e450-7f5c-49f3-91f0-5775b7bcc00f&quot;<br>}`</pre><h3>Step 2: Use the token to access resources through your RESTful API</h3><p>Use the token to access resources through your RESTful API</p><p>To access content available to all authenticated users:</p><ul><li>Use the generated token as the value of the Bearer in the Authorization header as follows: curl http://localhost:8080/springjwt/cities -H &quot;Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsidGVzdGp3dHJlc291cmNlaWQiXSwidXNlcl9uYW1lIjoiYWRtaW4uYWRtaW4iLCJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoxNDk0NDU0MjgyLCJhdXRob3JpdGllcyI6WyJTVEFOREFSRF9VU0VSIiwiQURNSU5fVVNFUiJdLCJqdGkiOiIwYmQ4ZTQ1MC03ZjVjLTQ5ZjMtOTFmMC01Nzc1YjdiY2MwMGYiLCJjbGllbnRfaWQiOiJ0ZXN0and0Y2xpZW50aWQifQ.rvEAa4dIz8hT8uxzfjkEJKG982Ree5PdUW17KtFyeec&quot;</li><li>The response will be: [ { &quot;id&quot;: 1, &quot;name&quot;: &quot;Bamako&quot; }, { &quot;id&quot;: 2, &quot;name&quot;: &quot;Nonkon&quot; }, { &quot;id&quot;: 3, &quot;name&quot;: &quot;Houston&quot; }, { &quot;id&quot;: 4, &quot;name&quot;: &quot;Toronto&quot; }, { &quot;id&quot;: 5, &quot;name&quot;: &quot;New York&quot; }, { &quot;id&quot;: 6, &quot;name&quot;: &quot;Mopti&quot; }, { &quot;id&quot;: 7, &quot;name&quot;: &quot;Koulikoro&quot; }, { &quot;id&quot;: 8, &quot;name&quot;: &quot;Moscow&quot; } ]</li></ul><p>To access content available only to an admin user:</p><p>As with the previous example, first, generate an access token for the admin user with the credentials provided above then run curl http://localhost:8080/springjwt/users -H &quot;Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsidGVzdGp3dHJlc291cmNlaWQiXSwidXNlcl9uYW1lIjoiYWRtaW4uYWRtaW4iLCJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoxNDk0NDU0OTIzLCJhdXRob3JpdGllcyI6WyJTVEFOREFSRF9VU0VSIiwiQURNSU5fVVNFUiJdLCJqdGkiOiIyMTAzMjRmMS05MTE0LTQ1NGEtODRmMy1hZjUzZmUxNzdjNzIiLCJjbGllbnRfaWQiOiJ0ZXN0and0Y2xpZW50aWQifQ.OuprVlyNnKuLkoQmP8shP38G3Hje91GBhu4E0HD2Fes&quot;</p><p>The result will be: [ { &quot;id&quot;: 1, &quot;username&quot;: &quot;john.doe&quot;, &quot;firstName&quot;: &quot;John&quot;, &quot;lastName&quot;: &quot;Doe&quot;, &quot;roles&quot;: [ { &quot;id&quot;: 1, &quot;roleName&quot;: &quot;STANDARD_USER&quot;, &quot;description&quot;: &quot;Standard User - Has no admin rights&quot; } ] }, { &quot;id&quot;: 2, &quot;username&quot;: &quot;admin.admin&quot;, &quot;firstName&quot;: &quot;Admin&quot;, &quot;lastName&quot;: &quot;Admin&quot;, &quot;roles&quot;: [ { &quot;id&quot;: 1, &quot;roleName&quot;: &quot;STANDARD_USER&quot;, &quot;description&quot;: &quot;Standard User - Has no admin rights&quot; }, { &quot;id&quot;: 2, &quot;roleName&quot;: &quot;ADMIN_USER&quot;, &quot;description&quot;: &quot;Admin User - Has permission to perform admin tasks&quot; } ] } ]</p><h3>9. Access a non-secure or non-protected endpoint</h3><p>The <a href="http://localhost/health">http://localhost:8080/health</a> is not restricted. This is accessible to anonymous users and can be used for load balancing health check purpose.</p><h3>References &amp; Useful Readings:</h3><ul><li>Spring Boot 1.5.3.RELEASE go to <a href="http://docs.spring.io/spring-boot/docs/1.5.3.RELEASE/reference/htmlsingle/">http://docs.spring.io/spring-boot/docs/1.5.3.RELEASE/reference/htmlsingle/</a> to learn more about spring boot</li><li>JSON Web Token go to <a href="https://jwt.io/">https://jwt.io/</a> to decode your generated token and learn more</li><li>H2 Database Engine — used for rapid prototyping and development, but not suitable for production at least in most cases. Go to <a href="http://www.h2database.com/">www.h2database.com</a> to learn more</li><li>Why you need to set <strong>security.oauth2.resource.filter-order = 3 </strong>in application.properties file<strong>: </strong><a href="https://docs.spring.io/spring-security/oauth/apidocs/org/springframework/security/oauth2/config/annotation/web/configuration/EnableResourceServer.html">https://docs.spring.io/spring-security/oauth/apidocs/org/springframework/security/oauth2/config/annotation/web/configuration/EnableResourceServer.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cd9f52381a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SPRING DATA JPA]]></title>
            <link>https://medium.com/@sendvjs/spring-data-jpa-af0f0c0c78a2?source=rss-3ec6a97bfa28------2</link>
            <guid isPermaLink="false">https://medium.com/p/af0f0c0c78a2</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[jpa]]></category>
            <dc:creator><![CDATA[Vikram]]></dc:creator>
            <pubDate>Thu, 18 Jun 2020 10:32:37 GMT</pubDate>
            <atom:updated>2020-06-18T10:32:37.176Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is JPA?</h3><p>JPA, short for the Java Persistence API, is a Java API that maps data from the database into an object in the Java language, reducing the burden of coding and making database management more efficient. Between the Object Model and the Relation Model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H1aYdKz4fDea4oqQ.png" /></figure><p>The ability of JPA is to extract data from the Database and convert it into an Object of the Java language and can convert the Object of the Java language into Database data. This is a benefit of JPA that programmers do not need to write a Query Statement to handle. Chilling information Even if you rely on the capabilities of the IDE, then Generate it for just a moment.</p><h3>Want to use JPA, what to do?</h3><p>Because JPA is an API (Application Programming Interface), Inteface is not yet available! Must implement first. Therefore, if we want to try What makes me happy is to find a good provider. Currently, there are many providers to implement such as Hibernate, Eclipselink, Spring Data JPA, etc. Each has its advantages and disadvantages as normal. However, try to study and choose the most suitable for the job</p><h3>Spring Data JPA</h3><p>If we want to call spring data jpa, we have to call through the Query method interface that JPA implements for us. findByFirstnameOrderByCreateDateDesc Refers to extract data from Column Name = firstname by extracting and creating with Desc CreateDate.</p><p>So it works like this when compared to Query SQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/0*BnvYyALathtXmS5X.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/0*_qqzYgaC5WbEzqIB.png" /></figure><ul><li>find = is a search for information similar to the selection in the Database</li><li>By = is a filter that needs to be similar to where in a Database</li><li>OrderBy … Asc, OrderBy … Desc = is a sorting of data similar to ordering by objects in the database.</li></ul><p>The good thing about it is that we can write it in human language to retrieve the data and it provides a lot of interface. Makes it easy to run</p><h3>Start using Spring Data JPA.</h3><p>We will use <a href="http://start.spring.io/">Spring Initializr</a> to build our project, create a project and choose dependencies as follows:</p><ul><li>Web is a Starter dependency for creating a web site that includes RESTful, Spring MVC and embedded tomcat by default.</li><li>JPA (Java Persistence API)</li><li>H2, we will use H2 which is in memory database.</li><li>Lombok, which is an annotation processing, helps code generation, such as reducing Getter Setter by adding annotation instead.</li></ul><p>After selecting the dependencies, you can click the Generate Project button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Tl9RPaLXUOkJ1TvI.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XphCTJN7PzvewrCK.png" /></figure><p>Spring Initializr will load the file to us about this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/0*bw42WzjfMIv84CWt.png" /></figure><p>Once done, you can insert the file into our project. Here, we can use the Spring Data JPA.</p><p>In the Spring Initializr file that Generate for you will include the dependencies we have chosen as follows:</p><h3>Dependencies</h3><pre>&lt;dependencies&gt;<br>	&lt;dependency&gt;<br>		&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>		&lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>	&lt;/dependency&gt;<br>	&lt;dependency&gt;<br>		&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>		&lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>	&lt;/dependency&gt;<br><br>	&lt;dependency&gt;<br>		&lt;groupId&gt;com.h2database&lt;/groupId&gt;<br>		&lt;artifactId&gt;h2&lt;/artifactId&gt;<br>		&lt;scope&gt;runtime&lt;/scope&gt;<br>	&lt;/dependency&gt;<br>	&lt;dependency&gt;<br>		&lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>		&lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>		&lt;optional&gt;true&lt;/optional&gt;<br>	&lt;/dependency&gt;<br>	&lt;dependency&gt;<br>		&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>		&lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>		&lt;scope&gt;test&lt;/scope&gt;<br>	&lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><h3>Config port</h3><p>Corrected the new port to 9090.</p><pre>server.port = 9090<br>spring.application.name = demoservice</pre><h3>Person Entity</h3><p>Create a Class Person and add the JPA annotations as follows.</p><ul><li>@Entity is to define a class as an entity.</li><li>@Id is the assignment of the primary key of the entity</li><li>@GeneratedValue Tells the generation values ​​for the primary key. GenerationType.AUTO means time inert new data. The system will generate the id automatically.</li><li>@Column is used to specify the name of the columns in our tables.</li><li>@Getter @Setter is set to get get set. We do not need to create our own dependencies. Lombok is our handle.</li></ul><pre>@Entity<br>public class Person {<br><br>	@Id<br>	@GeneratedValue(strategy = GenerationType.AUTO)<br>	@Getter<br>	private long id;<br><br>	@Getter @Setter<br>	private String firstName;<br>	<br>	@Getter @Setter<br>	private String lastName;<br><br>	protected Person() {}<br>	<br>	public Person(String firstName, String lastName) {<br>		this.firstName = firstName;<br>		this.lastName = lastName;<br>	}<br>	<br>	@Override<br>	public String toString() {<br>		/*<br>		 * return String.format( &quot;Person[id=%d, firstName=&#39;%s&#39;, lastName=&#39;%s&#39;]&quot;<br>		 * , id, firstName, lastName);<br>		 */<br>	return String.format(&quot;%d = %s %s&quot;, id, firstName, lastName);<br>	}<br>}</pre><h3>MemberRepo</h3><p>Then create PersonRepository as follows</p><ul><li>findByFirstName =&gt; … where firstname =? 1</li><li>findByLastName =&gt; … where lastname =? 1</li><li>findByFirstNameOrLastName =&gt; … where firstname =? 1 or lastname =? 2</li><li>findByFirstNameOrLastName =&gt; … where firstname =? 1 and lastname =? 2</li></ul><pre>public interface PersonRepository extends PagingAndSortingRepository&lt;Person, Long&gt; {<br><br>	List&lt;Person&gt; findByFirstName(@Param(&quot;name&quot;) String name);<br>	List&lt;Person&gt; findByLastName(@Param(&quot;name&quot;) String name);<br><br>	List&lt;Person&gt; findByFirstNameOrLastName(@Param(&quot;fname&quot;) String firstName,@Param(&quot;lname&quot;) String lastName);<br>	List&lt;Person&gt; findByFirstNameAndLastName(@Param(&quot;fname&quot;) String firstName,@Param(&quot;lname&quot;) String lastName);<br><br>}</pre><h3>DemoApplication adds CommandLineRunner</h3><p>Below is a simple code that uses CommandLineRunner. Bean uses CommandLineRunner. Will work immediately after the Spring application context has been initialized. We create a bean using CommandLineRunner and Save Data to the DB to have data for browsing.</p><pre>@SpringBootApplication<br>public class DemoApplication {<br>	private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);<br>	<br>	public static void main(String[] args) {<br>		SpringApplication.run(DemoApplication.class, args);<br>	}<br>	<br>	@Bean<br>	public CommandLineRunner demo(PersonRepository repository) {<br>		return (args) -&gt; {<br>			<br>			// save a couple of customers<br>			repository.save(new Person(&quot;Jack&quot;, &quot;Bauer&quot;));<br>			repository.save(new Person(&quot;Chloe&quot;, &quot;O&#39;Brian&quot;));<br>			repository.save(new Person(&quot;Kim&quot;, &quot;Bauer&quot;));<br>			repository.save(new Person(&quot;David&quot;, &quot;Palmer&quot;));<br>			repository.save(new Person(&quot;Michelle&quot;, &quot;Dessler&quot;));<br><br>			// fetch all customers<br>			log.info(&quot;Person found with findAll():&quot;);<br>			log.info(&quot;-------------------------------&quot;);<br>			for (Person person : repository.findAll()) {<br>				log.info(person.toString());<br>			}<br>			log.info(&quot;-------------------------------&quot;);<br>		};<br>	}<br>}</pre><h3>Maincontroller</h3><p>Create a MainController In order to be able to use the web via Rest api.</p><p>Which has method to call, call as follows</p><ul><li>home () for accessing the first page of the website on what to show</li><li>showAllPerson () for showing all Person data in the DB</li><li>searchPerson () for search FirstName = ‘David’ or LastName = ‘David’</li><li>insertPerson () for inserting Person Name = ‘Kim Jisoo’</li><li>deletePerson () for deleting Person Name = ‘Jack Bauer’</li></ul><pre>@Controller<br>public class MainController {<br>	<br>	@Autowired<br>    	private PersonRepository personRepository;<br>	<br>	@ResponseBody<br>	@RequestMapping(&quot;/&quot;)<br>	public String home() {<br>		String html = &quot;&quot;;<br>		html += &quot;&lt;ul&gt;&quot;;<br>		html += &quot; &lt;li&gt;&lt;a href=&#39;/showAllPerson&#39;&gt;Show All Person&lt;/a&gt;&lt;/li&gt;&quot;;<br>		html += &quot; &lt;li&gt;&lt;a href=&#39;/searchPerson&#39;&gt;Search Person Name = &#39;David&#39;&lt;/a&gt;&lt;/li&gt;&quot;;<br>		html += &quot; &lt;li&gt;&lt;a href=&#39;/insertPerson&#39;&gt;Insert Person Name = &#39;Kim Jisoo&#39;&lt;/a&gt;&lt;/li&gt;&quot;;<br>		html += &quot; &lt;li&gt;&lt;a href=&#39;/deletePerson&#39;&gt;Delete Person Name = &#39;Jack Bauer&#39;&lt;/a&gt;&lt;/li&gt;&quot;;<br>		html += &quot;&lt;/ul&gt;&quot;;<br>		return html;<br>	}<br>	<br>	@ResponseBody<br>    	@RequestMapping(&quot;/showAllPerson&quot;)<br>    	public String showAllPerson() {<br>		Iterable&lt;Person&gt; person = this.personRepository.findAll();<br><br>		String html = &quot;&quot;;<br>		if (person != null) {<br>			for (Person emp : person) {<br>			html += emp + &quot;&lt;br&gt;&quot;;<br>		    }<br>		}<br>		html += &quot;&lt;br&gt;&lt;a href=&#39;/&#39;&gt;Back To Home Page&lt;/a&gt;&quot;;<br>		return html;<br>   	 }<br>	<br>	@ResponseBody<br>    	@RequestMapping(&quot;/searchPerson&quot;)<br>    	public String searchPerson() {<br>		String html = &quot;Test Search Person Name = &#39;David&#39;&lt;br&gt;&quot;;<br>		List&lt;Person&gt; person = this.personRepository.findByFirstNameOrLastName(&quot;David&quot;, &quot;David&quot;);<br><br>		if (person != null) {<br>			for (Person emp : person) {<br>			html += emp + &quot;&lt;br&gt;&quot;;<br>		    }<br>		}<br>		html += &quot;&lt;br&gt;&lt;a href=&#39;/&#39;&gt;Back To Home Page&lt;/a&gt;&quot;;<br>		return html;<br>    	}<br>	<br>	@ResponseBody<br>    	@RequestMapping(&quot;/insertPerson&quot;)<br>		public String insertPerson() {<br>		String html = &quot;Test Insert Person Name = &#39;Kim Jisoo&#39;&lt;br&gt;&quot;;<br>			Person person = new Person(&quot;Kim&quot;, &quot;Jisoo&quot;);<br>		this.personRepository.save(person);<br>		html += &quot;Inserted: &quot; + person + &quot;&lt;br&gt;&lt;br&gt;&lt;a href=&#39;/&#39;&gt;Back To Home Page&lt;/a&gt;&quot;;<br>		return html;<br>    	}<br>	<br>	@ResponseBody<br>    	@RequestMapping(&quot;/deletePerson&quot;)<br>    	public String deletePerson() {<br>		String html = &quot;Test delete Person Name = &#39;Jack Bauer&#39;&lt;br&gt;&quot;;<br>		List&lt;Person&gt; person = this.personRepository.findByFirstNameAndLastName(&quot;Jack&quot;, &quot;Bauer&quot;);<br>		if (person != null &amp;&amp; !person.isEmpty()) {<br>			//this.personRepository.deleteById(person.get(0).getId());<br>			this.personRepository.delete(person.get(0));<br>		}<br>        	html += &quot;Deleted: &#39;Jack Bauer&#39; &lt;br&gt;&lt;br&gt;&lt;a href=&#39;/&#39;&gt;Back To Home Page&lt;/a&gt; &lt;br&gt;&lt;br&gt;&quot;;       <br>        	return html;<br>    	}<br>}</pre><h3>Test</h3><p>Run the application. The system will print the Person data that we initialized from Method CommandLineRunner in Class DemoApplication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yjXfj45gVe5dNfi-.png" /></figure><p>Enter the page via link =&gt; <a href="http://localhost:9090/">http: // localhost: 9090 /</a></p><h3>You can download the code from here to try it immediately.</h3><p>Link: <a href="https://github.com/vikramjitsaha/poc/blob/master/spring-data-jpa-master.zip">https://github.com/vikramjitsaha/poc/blob/master/spring-data-jpa-master.zip</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af0f0c0c78a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Difference between @Component, @Service, @Controller, and @Repository in Spring]]></title>
            <link>https://medium.com/@sendvjs/difference-between-component-service-controller-and-repository-in-spring-5f9fa05bcb1d?source=rss-3ec6a97bfa28------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f9fa05bcb1d</guid>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Vikram]]></dc:creator>
            <pubDate>Wed, 17 Jun 2020 20:49:09 GMT</pubDate>
            <atom:updated>2020-06-17T20:49:09.358Z</atom:updated>
            <content:encoded><![CDATA[<p>Before you learn the difference between @Component, @Service, @Controller, and @Repository annotations in the Spring Framework, it’s important to understand the role of @Component annotation in Spring. During the initial release of Spring, all beans are used to be declared in an XML file. For a large project, this quickly becomes a massive task, and Spring guys recognize the problem rather quickly. In later versions, they provide annotation-based dependency injection and Java-based configuration. From Spring 2.5 annotation-based dependency injection was introduced, which automatically scans and registers classes as Spring bean which is annotated using @Component annotation.</p><p>This means you don’t declare that bean using the &lt;bean&gt; tag and inject the dependency, it will be done automatically by Spring. This functionality was enabled and disabled using &lt;context:component-scan&gt; tag.</p><p>Now that you know what does @Component annotation does let’s see what does @Service, @Controller, and @Repository annotation do.</p><p>They are nothing but the specialized form of @Component annotation for certain situations. Instead of using @Component on a controller class in Spring MVC, we use @Controller, which is more readable and appropriate.</p><p>By using that annotation we do two things, first, we declare that this class is a Spring bean and should be created and maintained by Spring ApplicationContext, but also we indicate that its a controller in MVC setup. This latter property is used by web-specific tools and functionalities.</p><p>For example, DispatcherServlet will look for @RequestMapping on classes that are annotated using @Controller but not with @Component.</p><p>This means @Component and @Controller are the same with respect to bean creation and dependency injection but later is a specialized form of former. Even if you replace @Controller annotation with @Component, Spring can automatically detect and register the controller class but it may not work as you expect with respect to request mapping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/0*4-Vx0IhHgNFX0SPt.png" /></figure><p>The same is true for @Service and @Repository annotation, they are a specialization of @Component in service and persistence layer. A Spring bean in the service layer should be annotated using @Service instead of @Component annotation and a spring bean in the persistence layer should be annotated with @Repository annotation.</p><p>By using a specialized annotation we hit two birds with one stone. First, they are treated as Spring bean, and second, you can put special behavior required by that layer.</p><p>For example, @Repository’s not only helping in annotation based configure but also catch Platform-specific exceptions and re-throw them as one of Spring’s unified unchecked exception.</p><p>Though for that you also need to declare org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor as Spring bean in your application context.</p><p>This bean post-processor adds an advisor to any bean that’s annotated with @Repository so that any platform-specific exceptions are caught and then rethrown as one of Spring’s unchecked data access exceptions.</p><p>This is also one of the frequently asked Spring Interview Question and a popular concept from the Spring certification perspective. You will find a couple of questions based on these annotations and their usage in the Spring professional certification exam too.</p><h3>How does Component Scanning work in Spring?</h3><p>From Spring 2.0, Spring provides &lt;context:component-scan&gt; and annotation-driven dependency injection to automatically detect and register Spring bean instead of specifying them in the XML file.</p><p>But, it only scans @Component and does not look for @Controller, @Service, and @Repository in general. They are scanned because they themselves are annotated with @Component.</p><p>Just take a look at @Controller, @Service, and @Repository annotation definitions:</p><p>@Component<br>public @interface Service {<br>….<br>}</p><p>@Component<br>public @interface Repository {<br>….<br>}</p><p>@Component<br>public @interface Controller {<br>…<br>}</p><p>Thus, it’s not wrong to say that @Controller, @Service, and @Repository are special types of @Component annotation. &lt;context:component-scan&gt; picks them up and registers their following classes as beans, just as if they were annotated with @Component.</p><p>They are scanned because they themselves are annotated with @Component annotation. If you define your own custom annotation and annotate it with @Component, then it will also get scanned with &lt;context:component-scan&gt;.</p><h3>Difference between @Component, @Service, @Controller, and @Repository in Spring</h3><p>Here is a nice summary of what does @Component, @Service, @Controller, and @Repository annotation do in Spring Framework:</p><ol><li>@Component is a generic stereotype for any Spring-managed component or bean.</li><li>@Repository is a stereotype for the persistence layer.</li><li>@Service is a stereotype for the service layer.</li><li>@Controller is a stereotype for the presentation layer (spring-MVC).</li></ol><p>And here is the nice diagram to explain the hierarchy of all these annotations in Spring Framework:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/0*2DFquhd89vg0sXQl.jpg" /><figcaption>Annotations Inheritance</figcaption></figure><p>That’s all about the <strong>difference between @Component, @Controller, @Service, and @Repository in Spring Framework</strong>. As I said, all of them are used to auto-detect Spring beans when context scanning is enabled and essentially provide the same functionality with respect to dependency injection.</p><p>Their only difference comes in their purpose i.e. @Controller is used in Spring MVC to define controller, which are first Spring bean and then the controller. Similarly, @Service is used to annotated classes that hold business logic in the Service layer and @Repository is used in the Data Access layer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f9fa05bcb1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>