<?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 Georgios Nikolaos Palaiologopoulos on Medium]]></title>
        <description><![CDATA[Stories by Georgios Nikolaos Palaiologopoulos on Medium]]></description>
        <link>https://medium.com/@geonikpal?source=rss-a724af3d3d97------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1Gr-6iarwI60Wp0LPsMx8w.jpeg</url>
            <title>Stories by Georgios Nikolaos Palaiologopoulos on Medium</title>
            <link>https://medium.com/@geonikpal?source=rss-a724af3d3d97------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 15:49:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@geonikpal/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[Ternary Operator in Java]]></title>
            <link>https://medium.com/@geonikpal/ternary-operator-in-java-875dac6196b2?source=rss-a724af3d3d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/875dac6196b2</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ternary-operator]]></category>
            <category><![CDATA[core-java]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Georgios Nikolaos Palaiologopoulos]]></dc:creator>
            <pubDate>Sun, 02 Jun 2024 09:57:17 GMT</pubDate>
            <atom:updated>2024-06-02T09:57:17.193Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7AjztmQaMBOghlNUWtSxQ.png" /></figure><p>In this article, we’ll go through what the Ternary Operator is in Java and how it works.</p><h3>1. What is Ternary Operator in Java?</h3><p>The ternary operator is the ? followed by 2 : and it can be used to assign a value to a variable based on the truthiness of a condition. The syntax of the ternary operator is the following:</p><pre>Object_type_or_primitive variable_name =  boolean_value ? value_if_boolean_true : value_if_boolean_false;</pre><p>Of course, you can use it not only in assignments but when returning a value as it is shown below:</p><pre>return boolean_value ? value_if_boolean_true : value_if_boolean_false;</pre><p>This means that the value to be returned will be value_if_boolean_true if boolean_value is true and value_if_boolean_false if boolean_value is false.</p><p>Additionally, the value_if_boolean_true or value_if_boolean_false could be the result of another ternary operator calculation as shown below:</p><pre>return boolean_value ? <br>another_boolean_value ? value_if_another_boolean_value_true : value_if_another_boolean_value_false<br>: value_if_boolean_false;</pre><p>To completely understand this, the above snippet would be exactly the same as the snippet below:</p><pre>if(boolean_value){<br>  if(another_boolean_value){<br>    return value_if_another_boolean_value_true;<br>  }<br>  else {<br>    return value_if_another_boolean_value_false;<br>  }<br>}<br>else {<br>  return value_if_boolean_false;<br>}</pre><p>Although the ternary operator can make your code very concise, it has some limitations:</p><ul><li>It must always return a value, therefore you wouldn’t be able to convert this if statement to ternary operator statement:</li></ul><pre>public static int checkNumber(int x){<br>    if (x &gt;= 0){<br>        return x;<br>    }<br>    else {<br>        throw new IllegalArgumentException(&quot;The number cannot be negative&quot;);<br>    }<br>}</pre><ul><li>It might lead to unreadable code if there are a lot of ternary operators inside ternary operators, so you’d better choose if or switch statement.</li></ul><h3>2. Ternary Operator Example</h3><p>Let’s say you would like to implement an abs function, which will return the absolute value of a number. You could of course implement it using an if statement, but with the ternary operator, it is just one line of code as shown below:</p><pre>public static double abs(double x) {<br>    return x &gt;= 0 ? x : -x;<br>}</pre><p>You can also use it in assignments as already stated in the first section:</p><pre>public static void printPositiveness(int x) {<br>    String xString = x &gt;= 0 ?<br>           x == 0 ? &quot;x is zero&quot; : &quot;x is greater than zero&quot;<br>            : &quot;x is negative&quot;;<br>    System.out.println(xString);<br>}</pre><p>Here we assign the returned value of the ternary operator to the xString variable. Also, we demonstrated how you can use the ternary operator inside a ternary operator. The flow of the above snippet is the following:</p><ul><li>Is x greater than or equal 0?<br>- If yes, is x equal to zero?<br> - Then return &quot;x is zero&quot;.<br>- If not, then return &quot;x is greater than zero&quot;.</li><li>If not, return &quot;x is negative&quot;.</li></ul><h3>3. Conclusion</h3><p>By now you should be able to take full advantage of Java Ternary Operator and make your code more concise when possible. You can find the source code on my <a href="https://github.com/geonikpal/youlearncode-tutorials/blob/java-ternary-operator/java-ternary-operator/src/TernaryOperatorExample.java">GitHub page</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=875dac6196b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[@Transactional in Spring Boot]]></title>
            <link>https://medium.com/@geonikpal/transactional-in-spring-boot-23c6ffc4ee7d?source=rss-a724af3d3d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/23c6ffc4ee7d</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[transactional]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Georgios Nikolaos Palaiologopoulos]]></dc:creator>
            <pubDate>Sun, 25 Jun 2023 10:00:55 GMT</pubDate>
            <atom:updated>2024-06-20T10:56:23.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yWTaa9NgGOxFJg9zy51UGA.png" /></figure><p>In this article, we’ll talk about @Transactional in Spring Boot, and how it works, through detailed examples.</p><h3>1. What is @Transactional Annotation?</h3><p>The @Transactional annotation is used to mark a class or a method as transactional.</p><p>More specifically, when you mark a method as transactional, it means that this method should be treated as a single unit. More specifically, if any of the code fails inside a transaction, all the lines that had run before the line that caused the failure will be undone.</p><p>Of course, you can use the attributes provided to customize the behavior of the transaction, with regard to propagation, isolation, and when should or shouldn’t this transaction rollback.</p><h3>2. Setting Up the Project</h3><p>First of all, you need to have Java installed, if you do not you can go through these tutorials depending on the OS your machine runs:</p><ul><li>Linux users: <a href="https://www.java.com/download/">Install Java on Linux</a></li><li>macOS users: <a href="https://docs.oracle.com/javase/10/install/installation-jdk-and-jre-macos.htm">Install Java on macOS</a></li><li>Windows users: <a href="https://www.java.com/en/download/help/windows_manual_download.html">Install Java on Windows</a></li></ul><p>For this tutorial, we are using the <strong>IntelliJ IDEA Community edition</strong> which you can download <a href="https://www.jetbrains.com/idea/download/">here</a>.</p><p>If you are not using this IDE, you also need to download Maven <a href="https://maven.apache.org/download.cgi">here</a>.</p><p>The next step is to visit <a href="https://start.spring.io/">Spring initializr</a> and generate a project according to these settings shown in the image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eadbMBmUv_g-8Qbu.png" /></figure><p>After having chosen the above options, press the GENERATE button, and a new spring boot project will be downloaded for you. Then you have to unzip the compressed archive and open the folder with your favorite IDE.</p><h3>3. @Transactional Attributes Overview</h3><p>As we said before, @Transactional annotation allows you to customize how the method will behave; the attributes are the following:</p><ul><li>String value - the name of the transaction manager</li><li>String transactionManager - an alias to value</li><li>String[] label- the labels used to describe a transaction</li><li>Propagation propagation - the propagation mode of the transaction, defaults to REQUIRED</li><li>Isolation isolation - the isolation mode of the transaction, defaults to DEFAULT</li><li>int timeout - defines the timeout of the transaction in seconds</li><li>String timeoutString - defines the timeout of the transaction</li><li>boolean readOnly - defaults to false, can be set to true if the transaction is read-only, allowing for run-time optimizations</li><li>Class[] rollbackFor - specify which of the checked exceptions should cause a rollback. It accepts Classes e.g. FileNotFoundException.class</li><li>String[] rollbackForClassName - specify which of the checked exceptions should cause a rollback. It accepts Strings e.g. &quot;java.io.FileNotFoundException&quot;</li><li>Class[] noRollbackFor - specify which of the exceptions should <strong>NOT</strong> cause a rollback. It accepts Classes e.g. FileNotFoundException.class</li><li>String[] noRollbackForClassName - specify which of the exceptions should <strong>NOT</strong> cause a rollback. It accepts Strings e.g. &quot;java.io.FileNotFoundException&quot;</li></ul><p>In the following sections, we’ll dig deep into the most interesting ones(propagation, isolation, rollback, and noRollbackFor)</p><h3>4. Setting up the Project Base</h3><p>Before we begin, we have to declare the following classes.</p><p><strong>Car.java</strong>, the POJO that we will use in the examples:</p><pre>package com.youlearncode.transactionalAnnotation;<br><br>import java.util.Objects;<br><br>public class Car {<br><br>    private Integer id;<br>    private String model;<br>    private String brand;<br>    private Integer horsePower;<br>    private Double price;<br><br>    public Car() {}<br><br>    public Car(Integer id, String model, String brand, Integer horses, Double price) {<br>        this.id = id;<br>        this.model = model;<br>        this.brand = brand;<br>        this.horsePower = horses;<br>        this.price = price;<br>    }<br><br>    public Integer getId() {<br>        return id;<br>    }<br><br>    public void setId(Integer id) {<br>        this.id = id;<br>    }<br><br>    public String getModel() {<br>        return model;<br>    }<br><br>    public void setModel(String model) {<br>        this.model = model;<br>    }<br><br>    public String getBrand() {<br>        return brand;<br>    }<br><br>    public void setBrand(String brand) {<br>        this.brand = brand;<br>    }<br><br>    public Integer getHorsePower() {<br>        return horsePower;<br>    }<br><br>    public void setHorsePower(Integer horsePower) {<br>        this.horsePower = horsePower;<br>    }<br><br>    public Double getPrice() {<br>        return price;<br>    }<br><br>    public void setPrice(Double price) {<br>        this.price = price;<br>    }<br><br>    @Override<br>    public boolean equals(Object o) {<br>        if (this == o) return true;<br>        if (!(o instanceof Car)) return false;<br>        Car car = (Car) o;<br>        return Objects.equals(id, car.id) &amp;&amp; Objects.equals(model, car.model) &amp;&amp; Objects.equals(brand, car.brand) &amp;&amp; Objects.equals(horsePower, car.horsePower) &amp;&amp; Objects.equals(price, car.price);<br>    }<br><br>    @Override<br>    public int hashCode() {<br>        return Objects.hash(id, model, brand, horsePower, price);<br>    }<br>}</pre><p><strong>AbstractCarRepository.java</strong>, the abstract repository that we’ll extend later, depending on the attribute</p><pre>package com.youlearncode.transactionalAnnotation;<br><br>import org.springframework.context.ApplicationContext;<br>import org.springframework.jdbc.core.JdbcTemplate;<br><br>public abstract class AbstractCarRepository {<br><br>    protected final JdbcTemplate jdbcTemplate;<br>    protected final ApplicationContext applicationContext;<br><br>    public AbstractCarRepository(JdbcTemplate jdbcTemplate, ApplicationContext applicationContext) {<br>        this.jdbcTemplate = jdbcTemplate;<br>        this.applicationContext = applicationContext;<br>    }<br>}</pre><p>Then, we will create a RestControllerAdvice class to use later in the examples:</p><pre>package com.youlearncode.transactionalAnnotation;<br><br>import org.springframework.http.HttpStatus;<br>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.jdbc.core.SingleColumnRowMapper;<br>import org.springframework.web.bind.annotation.ExceptionHandler;<br>import org.springframework.web.bind.annotation.ResponseStatus;<br><br>@org.springframework.web.bind.annotation.RestControllerAdvice<br>public class RestControllerAdvice {<br><br>    private final JdbcTemplate jdbcTemplate;<br><br>    public RestControllerAdvice(JdbcTemplate jdbcTemplate) {<br>        this.jdbcTemplate = jdbcTemplate;<br>    }<br><br>    @ExceptionHandler(value = Exception.class)<br>    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)<br>    public void carInsertError() {<br>        var count = jdbcTemplate.queryForObject(&quot;select count(id) from car&quot;, new SingleColumnRowMapper&lt;&gt;());<br>        System.out.println(&quot;Number of cars in db: &quot; + count);<br><br>    }<br>}</pre><p>Additionally, under resources, we will create a schema.sql and data.sql as shown below:</p><pre>CREATE TABLE car(<br>    id integer,<br>    model varchar(100),<br>    brand varchar(100),<br>    horsePower integer,<br>    price double precision<br>);</pre><pre>INSERT INTO car(id, model, brand, horsepower, price) values (1, &#39;Astra&#39;,&#39;Opel&#39;,120, 20000);</pre><p>Finally, add the following configurations in application.properties:</p><pre>spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE<br>spring.h2.console.enabled=true<br>logging.level.org.springframework.transaction.interceptor = TRACE<br>logging.level.org.springframework.transaction = TRACE<br>logging.level.org.springframework.transaction.support = TRACE</pre><h3>5. @Transactional Propagation Attribute</h3><p>For this attribute, we will have to create a new package named propagation, and inside of it, another package named setup.</p><p>Now inside this setup package, we will create 3 classes:</p><p><strong>CarRestController.java</strong></p><pre>package com.youlearncode.transactionalAnnotation.propagation.setup.controller;<br><br>import com.youlearncode.transactionalAnnotation.Car;<br>import com.youlearncode.transactionalAnnotation.propagation.setup.service.CarService;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.http.MediaType;<br>import org.springframework.web.bind.annotation.PostMapping;<br>import org.springframework.web.bind.annotation.RequestBody;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RequestParam;<br>import org.springframework.web.bind.annotation.RestController;<br><br>/**<br> * Rest Controller for cars<br> */<br>@RestController<br>@RequestMapping(value = &quot;/cars&quot;, produces = MediaType.APPLICATION_JSON_VALUE)<br>@Profile(&quot;propagation&quot;)<br>public class CarRestController {<br><br>    private final CarService carService;<br><br>    @Autowired<br>    public CarRestController(CarService carService) {<br>        this.carService = carService;<br>    }<br><br><br>    @PostMapping<br>    public void addCar(@RequestBody Car car) throws Exception {<br>        carService.insertAndUpdateCar(car);<br>    }<br>}</pre><p><strong>CarRepository.java</strong></p><pre>package com.youlearncode.transactionalAnnotation.propagation.setup.repository;<br><br>import com.youlearncode.transactionalAnnotation.Car;<br><br>public interface CarRepository {<br><br>    void insertCarAndUpdateCar(Car car) throws Exception;<br><br>    void updateCar(Car car, double percent) throws Exception;<br><br>}</pre><p>Finally, the <strong>CarService.java</strong>:</p><pre>package com.youlearncode.transactionalAnnotation.propagation.setup;<br><br>import com.youlearncode.transactionalAnnotation.Car;<br>import com.youlearncode.transactionalAnnotation.propagation.setup.CarRepository;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>@Profile(&quot;propagation&quot;)<br>public class CarService {<br><br>    protected final CarRepository carRepository;<br><br>    public CarService(CarRepository carRepository) {<br>        this.carRepository = carRepository;<br>    }<br><br>    public void insertAndUpdateCar(Car car) throws Exception {<br>        carRepository.insertCarAndUpdateCar(car);<br>    }<br>}</pre><p>The propagation of a transaction has to do with the behavior of a transaction when called from another transactional method. The @Transactional annotation has the following propagation options:</p><ul><li>REQUIRED</li><li>SUPPORTS</li><li>MANDATORY</li><li>REQUIRES_NEW</li><li>NOT_SUPPORTED</li><li>NEVER</li><li>NESTED</li></ul><h3>5.1 @Transactional(propagation = Propagation.REQUIRED)</h3><p>This option is the default, and it will act according to the following algorithm:</p><pre>if(transactionExists){<br>  useExistingTransaction()<br>} else {<br>  createNewTransaction()</pre><p>Now, to see it in action, we just have to create a class named CarRepositoryRequired that will extend the AbstractCarRepository and implement the CarRepository as follows:</p><pre>package com.youlearncode.transactionalAnnotation.propagation;<br><br>import com.youlearncode.transactionalAnnotation.AbstractCarRepository;<br>import com.youlearncode.transactionalAnnotation.Car;<br>import com.youlearncode.transactionalAnnotation.propagation.setup.repository.CarRepository;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.ApplicationContext;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.stereotype.Repository;<br>import org.springframework.transaction.annotation.Propagation;<br>import org.springframework.transaction.annotation.Transactional;<br>import org.springframework.transaction.support.TransactionSynchronizationManager;<br><br>@Repository<br>@Profile(&quot;propagation &amp; required&quot;)<br>public class CarRepositoryRequired extends AbstractCarRepository implements CarRepository {<br><br>    @Autowired<br>    public CarRepositoryRequired(JdbcTemplate jdbcTemplate, ApplicationContext applicationContext) {<br>        super(jdbcTemplate, applicationContext);<br>    }<br><br>    @Transactional(propagation = Propagation.REQUIRED)<br>    public void insertCarAndUpdateCar(Car car) throws Exception {<br>        jdbcTemplate.update(<br>                &quot;INSERT INTO car(id, model, brand, horsepower, price) values (?,?,?,?,?)&quot;,<br>                car.getId(), car.getModel(), car.getBrand(), car.getHorsePower(), car.getPrice()<br>        );<br>        var bean = ((CarRepositoryRequired) applicationContext.getBean(&quot;carRepositoryRequired&quot;));<br>        bean.updateCar(car, 0.1);<br>    }<br><br>    @Transactional(propagation = Propagation.REQUIRED)<br>    public void updateCar(Car car, double percent) throws Exception {<br>        System.out.println(&quot;Current Transaction: &quot; + TransactionSynchronizationManager.getCurrentTransactionName());<br>        System.out.println(&quot;Is active? &quot; + (TransactionSynchronizationManager.isActualTransactionActive()));<br>        jdbcTemplate.update(<br>                &quot;UPDATE car set price = ? where id = ?&quot;,<br>                car.getPrice() * (1 + percent), car.getId()<br>        );<br>    }<br>    <br>}</pre><p>Before you start the app, make sure that you have added this configuration in application.properties:</p><p>spring.profiles.active=propagation,required</p><p>Now let’s explain what happens here if we send a POST /cars with the following payload:</p><pre>{<br>    &quot;id&quot;: 2,<br>    &quot;model&quot; : &quot;Corsa&quot;,<br>    &quot;brand&quot; : &quot;Opel&quot;,<br>    &quot;horsePower&quot; :90,<br>    &quot;price&quot;: 18000<br>}</pre><p>Firstly, the controller will call the service and then the service will call the insertCarAndUpdateCar method of CarRepositoryRequired. Then we will use the update() method of JdbcTemplate to insert the car in the database.</p><p>Afterward, we retrieve the bean from the context(It is important to do so since the transactional annotation won’t work if we call directly the updateCar method, due to having the need to use a proxy) and we call the updateCar method.</p><p>Now since the updateCar has propagation required, the previous transaction will be used and the result to be printed will be:</p><pre>2023-06-18T20:19:31.602+03:00 TRACE 15216 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Getting transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequired.insertCarAndUpdateCar]<br>2023-06-18T20:19:31.611+03:00 TRACE 15216 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Getting transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequired.updateCar]<br>Current Transaction: com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequired.insertCarAndUpdateCar<br>Is active? true<br>2023-06-18T20:19:31.616+03:00 TRACE 15216 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Completing transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequired.updateCar]<br>2023-06-18T20:19:31.616+03:00 TRACE 15216 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Completing transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequired.insertCarAndUpdateCar]</pre><p>This means that the existing transaction was used.</p><p>On the other hand, if we remove the @Transactional annotation from the insertCarAndUpdateCar, we will see the following logs:</p><pre>2023-06-18T20:20:47.959+03:00 TRACE 9684 --- [nio-8080-exec-2] o.s.t.i.TransactionInterceptor           : Getting transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequired.updateCar]<br>Current Transaction: com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequired.updateCar<br>Is active? true<br>2023-06-18T20:20:47.964+03:00 TRACE 9684 --- [nio-8080-exec-2] o.s.t.i.TransactionInterceptor           : Completing transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequired.updateCar]</pre><p>This means that a new transaction was created.</p><h3>5.2 @Transactional(propagation = Propagation.SUPPORTS)</h3><p>This option will act according to the following algorithm:</p><pre>if(transactionExists){<br>  useExistingTransaction()<br>} else {<br>  doNotUseTransaction()<br>}</pre><p>Now, to see it in action, we just have to create a class named CarRepositorySupports that will extend the AbstractCarRepository and implement the CarRepository as follows:</p><pre>package com.youlearncode.transactionalAnnotation.propagation;<br><br>import com.youlearncode.transactionalAnnotation.AbstractCarRepository;<br>import com.youlearncode.transactionalAnnotation.Car;<br>import com.youlearncode.transactionalAnnotation.propagation.setup.repository.CarRepository;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.ApplicationContext;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.stereotype.Repository;<br>import org.springframework.transaction.annotation.Propagation;<br>import org.springframework.transaction.annotation.Transactional;<br>import org.springframework.transaction.support.TransactionSynchronizationManager;<br><br>@Repository<br>@Profile(&quot;propagation &amp; supports&quot;)<br>public class CarRepositorySupports extends AbstractCarRepository implements CarRepository {<br><br>    @Autowired<br>    public CarRepositorySupports(JdbcTemplate jdbcTemplate, ApplicationContext applicationContext) {<br>        super(jdbcTemplate, applicationContext);<br>    }<br><br>    @Transactional(propagation = Propagation.REQUIRED)<br>    public void insertCarAndUpdateCar(Car car) throws Exception {<br>        jdbcTemplate.update(<br>                &quot;INSERT INTO car(id, model, brand, horsepower, price) values (?,?,?,?,?)&quot;,<br>                car.getId(), car.getModel(), car.getBrand(), car.getHorsePower(), car.getPrice()<br>        );<br>        var bean = ((CarRepositorySupports) applicationContext.getBean(&quot;carRepositorySupports&quot;));<br>        bean.updateCar(car, 0.1);<br>    }<br><br>    @Transactional(propagation = Propagation.SUPPORTS)<br>    public void updateCar(Car car, double percent) throws Exception {<br>        System.out.println(&quot;Current Transaction: &quot; + TransactionSynchronizationManager.getCurrentTransactionName());<br>        System.out.println(&quot;Is active? &quot; + TransactionSynchronizationManager.isActualTransactionActive());<br>        jdbcTemplate.update(<br>                &quot;UPDATE car set price = ? where id = ?&quot;,<br>                car.getPrice() * (1 + percent), car.getId()<br>        );<br>    }<br><br><br>}</pre><p>Before you start the app, make sure that you have added this configuration in application.properties:</p><p>spring.profiles.active=propagation,supports</p><p>Like in the previous section, we will explain what happens here if we send a POST /cars with the following payload:</p><pre>{<br>    &quot;id&quot;: 2,<br>    &quot;model&quot; : &quot;Corsa&quot;,<br>    &quot;brand&quot; : &quot;Opel&quot;,<br>    &quot;horsePower&quot; :90,<br>    &quot;price&quot;: 18000<br>}</pre><p>This time, since the updateCar has propagation supports, the previous transaction will be used and as a result, the logs will be exactly like with required.</p><pre>2023-06-18T20:19:31.602+03:00 TRACE 15216 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Getting transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequired.insertCarAndUpdateCar]<br>2023-06-18T20:19:31.611+03:00 TRACE 15216 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Getting transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequired.updateCar]<br>Current Transaction: com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequired.insertCarAndUpdateCar<br>Is active? true<br>2023-06-18T20:19:31.616+03:00 TRACE 15216 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Completing transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequired.updateCar]<br>2023-06-18T20:19:31.616+03:00 TRACE 15216 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Completing transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequired.insertCarAndUpdateCar]</pre><p>However, if we remove the @Transactional annotation from the updateCar, we will see the following logs:</p><pre>2023-06-18T20:33:05.344+03:00 TRACE 6848 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Getting transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositorySupports.updateCar]<br>Current Transaction: com.youlearncode.transactionalAnnotation.propagation.CarRepositorySupports.updateCar<br>Is active? false<br>2023-06-18T20:33:05.350+03:00 TRACE 6848 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Completing transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositorySupports.updateCar]</pre><p>So no transaction was active inside the updateCar method.</p><h3>5.3 @Transactional(propagation = Propagation.MANDATORY)</h3><p>This option will act according to the following algorithm:</p><pre>if(transactionExists){ useExistingTransaction() } else { throwException() }</pre><p>Now, to see it in action, we just have to create a class named CarRepositoryMandatory that will extend the AbstractCarRepository and implement the CarRepository as follows:</p><pre>package com.youlearncode.transactionalAnnotation.propagation;<br><br>import com.youlearncode.transactionalAnnotation.AbstractCarRepository;<br>import com.youlearncode.transactionalAnnotation.Car;<br>import com.youlearncode.transactionalAnnotation.propagation.setup.repository.CarRepository;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.ApplicationContext;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.stereotype.Repository;<br>import org.springframework.transaction.annotation.Propagation;<br>import org.springframework.transaction.annotation.Transactional;<br>import org.springframework.transaction.support.TransactionSynchronizationManager;<br><br>@Repository<br>@Profile(&quot;propagation &amp; mandatory&quot;)<br>public class CarRepositoryMandatory extends AbstractCarRepository implements CarRepository {<br><br>    @Autowired<br>    public CarRepositoryMandatory(JdbcTemplate jdbcTemplate, ApplicationContext applicationContext) {<br>        super(jdbcTemplate, applicationContext);<br>    }<br><br>    @Transactional(propagation = Propagation.REQUIRED)<br>    public void insertCarAndUpdateCar(Car car) throws Exception {<br>        jdbcTemplate.update(<br>                &quot;INSERT INTO car(id, model, brand, horsepower, price) values (?,?,?,?,?)&quot;,<br>                car.getId(), car.getModel(), car.getBrand(), car.getHorsePower(), car.getPrice()<br>        );<br>        var bean = ((CarRepositoryMandatory) applicationContext.getBean(&quot;carRepositoryMandatory&quot;));<br>        bean.updateCar(car, 0.1);<br>    }<br><br>    @Transactional(propagation = Propagation.MANDATORY)<br>    public void updateCar(Car car, double percent) throws Exception {<br>        System.out.println(&quot;Current Transaction: &quot; + TransactionSynchronizationManager.getCurrentTransactionName());<br>        System.out.println(&quot;Is active? &quot; + TransactionSynchronizationManager.isActualTransactionActive());<br>        jdbcTemplate.update(<br>                &quot;UPDATE car set price = ? where id = ?&quot;,<br>                car.getPrice() * (1 + percent), car.getId()<br>        );<br>    }<br><br><br>}</pre><p>Before you start the app, make sure that you have added this configuration in application.properties:</p><p>spring.profiles.active=propagation,mandatory</p><p>Like in the previous section, we will explain what happens here if we send a POST /cars with the following payload:</p><pre>{<br>    &quot;id&quot;: 2,<br>    &quot;model&quot; : &quot;Corsa&quot;,<br>    &quot;brand&quot; : &quot;Opel&quot;,<br>    &quot;horsePower&quot; :90,<br>    &quot;price&quot;: 18000<br>}</pre><p>Again the logs will be the same:</p><pre>2023-06-18T20:19:31.602+03:00 TRACE 15216 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Getting transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequired.insertCarAndUpdateCar]<br>2023-06-18T20:19:31.611+03:00 TRACE 15216 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Getting transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequired.updateCar]<br>Current Transaction: com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequired.insertCarAndUpdateCar<br>Is active? true<br>2023-06-18T20:19:31.616+03:00 TRACE 15216 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Completing transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequired.updateCar]<br>2023-06-18T20:19:31.616+03:00 TRACE 15216 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Completing transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequired.insertCarAndUpdateCar]</pre><p>As you would expect if we remove the @Transactional from the insertCarAndUpdateCar method, no transaction will be created, and an exception will be thrown.</p><p>Of course, if you take a look at the database entries, you will see that no updates were made and the price of the car remained the same.</p><h3>5.4 @Transactional(propagation = Propagation.REQUIRES_NEW)</h3><p>This option will act according to the following algorithm:</p><pre>if(transactionExists){<br>  suspendCurrentAndCreateNew()<br>} else {<br>  createNew()<br>}</pre><p>Now, to see it in action, we just have to create a class named CarRepositoryRequiresNew that will extend the AbstractCarRepository and implement the CarRepository as follows:</p><pre>package com.youlearncode.transactionalAnnotation.propagation;<br><br>import com.youlearncode.transactionalAnnotation.AbstractCarRepository;<br>import com.youlearncode.transactionalAnnotation.Car;<br>import com.youlearncode.transactionalAnnotation.propagation.setup.repository.CarRepository;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.ApplicationContext;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.stereotype.Repository;<br>import org.springframework.transaction.annotation.Propagation;<br>import org.springframework.transaction.annotation.Transactional;<br>import org.springframework.transaction.support.TransactionSynchronizationManager;<br><br>@Repository<br>@Profile(&quot;propagation &amp; requiresnew&quot;)<br>public class CarRepositoryRequiresNew extends AbstractCarRepository implements CarRepository {<br><br>    @Autowired<br>    public CarRepositoryRequiresNew(JdbcTemplate jdbcTemplate, ApplicationContext applicationContext) {<br>        super(jdbcTemplate, applicationContext);<br>    }<br><br>    @Transactional(propagation = Propagation.REQUIRED)<br>    public void insertCarAndUpdateCar(Car car) throws Exception {<br>        jdbcTemplate.update(<br>                &quot;INSERT INTO car(id, model, brand, horsepower, price) values (?,?,?,?,?)&quot;,<br>                car.getId(), car.getModel(), car.getBrand(), car.getHorsePower(), car.getPrice()<br>        );<br>        var bean = ((CarRepositoryRequiresNew) applicationContext.getBean(&quot;carRepositoryRequiresNew&quot;));<br>        bean.updateCar(car, 0.1);<br>    }<br><br>    @Transactional(propagation = Propagation.REQUIRES_NEW)<br>    public void updateCar(Car car, double percent) throws Exception {<br>        System.out.println(&quot;Current Transaction: &quot; + TransactionSynchronizationManager.getCurrentTransactionName());<br>        System.out.println(&quot;Is active? &quot; + TransactionSynchronizationManager.isActualTransactionActive());<br>        jdbcTemplate.update(<br>                &quot;UPDATE car set price = ? where id = ?&quot;,<br>                car.getPrice() * (1 + percent), car.getId()<br>        );<br>    }<br><br><br>}</pre><p>Before you start the app, make sure that you have added this configuration in application.properties:</p><p>spring.profiles.active=propagation,requiresnew</p><p>Like in the previous section, we will explain what happens here if we send a POST /cars with the following payload:</p><pre>{<br>    &quot;id&quot;: 2,<br>    &quot;model&quot; : &quot;Corsa&quot;,<br>    &quot;brand&quot; : &quot;Opel&quot;,<br>    &quot;horsePower&quot; :90,<br>    &quot;price&quot;: 18000<br>}</pre><p>This time, since the updateCar has propagation requires_new, the previous transaction will be suspended and a new one will be created:</p><pre>2023-06-18T20:44:34.650+03:00 TRACE 12292 --- [nio-8080-exec-2] o.s.t.i.TransactionInterceptor           : Getting transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequiresNew.insertCarAndUpdateCar]<br>2023-06-18T20:44:34.659+03:00 TRACE 12292 --- [nio-8080-exec-2] o.s.t.i.TransactionInterceptor           : Getting transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequiresNew.updateCar]<br>Current Transaction: com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequiresNew.updateCar<br>Is active? true<br>2023-06-18T20:44:34.663+03:00 TRACE 12292 --- [nio-8080-exec-2] o.s.t.i.TransactionInterceptor           : Completing transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequiresNew.updateCar]<br>2023-06-18T20:44:34.664+03:00 TRACE 12292 --- [nio-8080-exec-2] o.s.t.i.TransactionInterceptor           : Completing transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryRequiresNew.insertCarAndUpdateCar]</pre><p>However, if we remove the @Transactional annotation from the updateCar, the logs will be the same as before since a new transaction will be created.</p><h3>5.6 @Transactional(propagation = Propagation.NEVER)</h3><p>This option will act according to the following algorithm:</p><pre>if(transactionExists){<br>  throwException()<br>} else {<br>  doNotUseTransaction()<br>}</pre><p>Now, to see it in action, we just have to create a class named CarRepositoryNever that will extend the AbstractCarRepository and implement the CarRepository as follows:</p><pre>package com.youlearncode.transactionalAnnotation.propagation;<br><br>import com.youlearncode.transactionalAnnotation.AbstractCarRepository;<br>import com.youlearncode.transactionalAnnotation.Car;<br>import com.youlearncode.transactionalAnnotation.propagation.setup.repository.CarRepository;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.ApplicationContext;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.stereotype.Repository;<br>import org.springframework.transaction.annotation.Propagation;<br>import org.springframework.transaction.annotation.Transactional;<br>import org.springframework.transaction.support.TransactionSynchronizationManager;<br><br>@Repository<br>@Profile(&quot;propagation &amp; never&quot;)<br>public class CarRepositoryNever extends AbstractCarRepository implements CarRepository {<br><br>    @Autowired<br>    public CarRepositoryNever(JdbcTemplate jdbcTemplate, ApplicationContext applicationContext) {<br>        super(jdbcTemplate, applicationContext);<br>    }<br><br>    @Transactional(propagation = Propagation.REQUIRED)<br>    public void insertCarAndUpdateCar(Car car) throws Exception {<br>        jdbcTemplate.update(<br>                &quot;INSERT INTO car(id, model, brand, horsepower, price) values (?,?,?,?,?)&quot;,<br>                car.getId(), car.getModel(), car.getBrand(), car.getHorsePower(), car.getPrice()<br>        );<br>        var bean = ((CarRepositoryNever) applicationContext.getBean(&quot;carRepositoryNever&quot;));<br>        bean.updateCar(car, 0.1);<br>    }<br><br>    @Transactional(propagation = Propagation.NEVER)<br>    public void updateCar(Car car, double percent) throws Exception {<br>        System.out.println(&quot;Current Transaction: &quot; + TransactionSynchronizationManager.getCurrentTransactionName());<br>        System.out.println(&quot;Is active? &quot; + TransactionSynchronizationManager.isActualTransactionActive());<br>        jdbcTemplate.update(<br>                &quot;UPDATE car set price = ? where id = ?&quot;,<br>                car.getPrice() * (1 + percent), car.getId()<br>        );<br>    }<br>    <br>}</pre><p>Before you start the app, make sure that you have added this configuration in application.properties:</p><p>spring.profiles.active=propagation,never</p><p>Like in the previous section, we will explain what happens here if we send a POST /cars with the following payload:</p><pre>{<br>    &quot;id&quot;: 2,<br>    &quot;model&quot; : &quot;Corsa&quot;,<br>    &quot;brand&quot; : &quot;Opel&quot;,<br>    &quot;horsePower&quot; :90,<br>    &quot;price&quot;: 18000<br>}</pre><p>With the Propagation type never, an exception will be thrown and the insertion will never happen. The logs that will be shown are the following:</p><pre>2023-06-18T20:55:59.382+03:00 TRACE 22360 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Getting transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryNever.insertCarAndUpdateCar]<br>2023-06-18T20:55:59.391+03:00 TRACE 22360 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Completing transaction for [com.youlearncode.transactionalAnnotation.propagation.CarRepositoryNever.insertCarAndUpdateCar] after exception: org.springframework.transaction.IllegalTransactionStateException: Existing transaction found for transaction marked with propagation &#39;never</pre><h3>5.7 @Transactional(propagation = Propagation.NESTED)</h3><p>This propagation behavior creates a nested transaction within the existing transaction. The nested transaction can be rolled back independently of the outer transaction. If an exception occurs within the nested transaction, only the changes made within that transaction will be rolled back, while the changes made in the outer transaction will remain intact.</p><h3>6. @Transactional Isolation Attribute</h3><p>For this attribute, we will have to create a new package named isolation, and inside of it, another package named setup.</p><p>Now inside this setup package, we will create 3 classes:</p><p><strong>CarRestController.java</strong></p><pre>package com.youlearncode.transactionalAnnotation.isolation.setup.controller;<br><br>import com.youlearncode.transactionalAnnotation.Car;<br>import com.youlearncode.transactionalAnnotation.isolation.setup.service.CarService;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.http.MediaType;<br>import org.springframework.web.bind.annotation.PostMapping;<br>import org.springframework.web.bind.annotation.RequestBody;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>/**<br> * Rest Controller for cars<br> */<br>@RestController<br>@RequestMapping(value = &quot;/cars&quot;, produces = MediaType.APPLICATION_JSON_VALUE)<br>@Profile(&quot;isolation&quot;)<br>public class CarRestController {<br><br>    private final CarService carService;<br><br>    @Autowired<br>    public CarRestController(CarService carService) {<br>        this.carService = carService;<br>    }<br><br><br>    @PostMapping<br>    public void addCar(@RequestBody Car car) throws Exception{<br>        carService.demonstrateIsolationType(car);<br>    }<br><br>}</pre><p><strong>CarRepository.java</strong></p><pre>package com.youlearncode.transactionalAnnotation.isolation.setup.repository;<br><br><br>import com.youlearncode.transactionalAnnotation.Car;<br><br>public interface CarRepository {<br><br>    void demonstrateIsolationType(Car car) throws Exception;<br><br>}</pre><p>The concept of isolation in transaction processing refers to how transactions interact with each other when accessing and modifying data in a concurrent environment. Isolation ensures that each transaction appears to execute independently of other transactions, even though they may be executed concurrently. The @Transactional annotation has the following isolation options:</p><ul><li>DEFAULT</li><li>READ_UNCOMMITTED</li><li>READ_COMMITTED</li><li>REPEATABLE_READ</li><li>SERIALIZABLE</li></ul><p>Note that, the DEFAULT option relies on the default isolation level that the data store uses. For example, MySQL uses the repeatable read isolation level, while for other data stores such as PostgreSQL and MS SQL, the default is the read committed level.</p><p>Before we begin, let’s explain some important concepts when it comes to isolation levels:</p><ol><li><strong>Dirty Read</strong>: The dirty read means that a transaction can read data that were modified by other transactions that have not been committed yet. As you can imagine, this can lead to handling inconsistent data</li><li><strong>Repeatable Read:</strong> Repeatable Read is a level of isolation in database transactions that makes sure that the transaction sees a stable and unchanging view of the data throughout its execution, making it so that other transactions cannot make changes to the data being read by the current transaction.</li><li><strong>Phantom Read</strong>: Phantom read refers to a phenomenon in database systems where a transaction sees a different set of rows in a query result due to concurrent transactions modifying the data. For example, let’s say Transaction A reads all rows from a table where the age is less than 30, and at the same time, Transaction B inserts a new row into the same table with an age of 25. If Transaction A performs the same query again immediately after Transaction B commits, it will encounter a phantom read because it now sees an additional row in the result set that was not present during its previous read.</li></ol><h3>6.1 READ_UNCOMMITTED &amp; READ_COMMITTED Isolation Levels</h3><h4>6.1.1 @Transactional(isolation = READ_UNCOMMITTED)</h4><blockquote><em>Remember to change the profiles in application.properties to spring.profiles.active=isolation,readuncommitted</em></blockquote><p>By choosing the Isolation.READ_UNCOMMITTED, you are enabling dirty reads, non-repeatable reads, and phantom reads. Now let&#39;s create the following class:</p><pre>package com.youlearncode.transactionalAnnotation.isolation;<br><br>import com.youlearncode.transactionalAnnotation.AbstractCarRepository;<br>import com.youlearncode.transactionalAnnotation.Car;<br>import com.youlearncode.transactionalAnnotation.isolation.setup.repository.CarRepository;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.ApplicationContext;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.jdbc.core.SingleColumnRowMapper;<br>import org.springframework.stereotype.Repository;<br>import org.springframework.transaction.annotation.Isolation;<br>import org.springframework.transaction.annotation.Propagation;<br>import org.springframework.transaction.annotation.Transactional;<br>import org.springframework.transaction.support.TransactionSynchronizationManager;<br><br>@Repository<br>@Profile(&quot;readuncommitted &amp; isolation&quot;)<br>public class CarRepositoryReadUncommitted extends AbstractCarRepository implements CarRepository {<br><br>    @Autowired<br>    public CarRepositoryReadUncommitted(JdbcTemplate jdbcTemplate, ApplicationContext applicationContext) {<br>        super(jdbcTemplate, applicationContext);<br>    }<br><br>    @Transactional<br>    public void demonstrateIsolationType(Car car) throws Exception {<br>        jdbcTemplate.update(<br>                &quot;INSERT INTO car(id, model, brand, horsepower, price) values (?,?,?,?,?)&quot;,<br>                car.getId(), car.getModel(), car.getBrand(), car.getHorsePower(), car.getPrice()<br>        );<br>        var bean = applicationContext.getBean(&quot;carRepositoryReadUncommitted&quot;, CarRepositoryReadUncommitted.class);<br>        bean.printNumberOfCars();<br>    }<br><br>    @Transactional(isolation = Isolation.READ_UNCOMMITTED, propagation = Propagation.REQUIRES_NEW)<br>    public void printNumberOfCars() throws Exception {<br>        System.out.println(&quot;Current Transaction: &quot; + TransactionSynchronizationManager.getCurrentTransactionName());<br>        System.out.println(&quot;Is active? &quot; +<br>                 TransactionSynchronizationManager.isActualTransactionActive());<br>        var count = jdbcTemplate.queryForObject(&quot;select count(id) from car&quot;, new SingleColumnRowMapper&lt;&gt;());<br>        System.out.println(&quot;Number of cars in db: &quot; + count);<br>    }<br><br>}</pre><p>In the above scenario, consider that we have already added one car to the database. Then when we hit the POST /cars with the following payload:</p><pre>{<br>    &quot;id&quot;: 2,<br>    &quot;model&quot; : &quot;Corsa&quot;,<br>    &quot;brand&quot; : &quot;Opel&quot;,<br>    &quot;horsePower&quot; :90,<br>    &quot;price&quot;: 18000<br>}</pre><p>The car will be inserted into the database. However, we call the printNumberOfCars() method before the transaction ends, and therefore, when we print the number of cars inside the printNumberOfCars() method, the result will be the following:</p><pre>2023-06-24T22:14:39.382+03:00 TRACE 17236 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Getting transaction for [com.youlearncode.transactionalAnnotation.isolation.CarRepositoryReadUncommitted.demonstrateIsolationType]<br>2023-06-24T22:14:39.392+03:00 TRACE 17236 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Getting transaction for [com.youlearncode.transactionalAnnotation.isolation.CarRepositoryReadUncommitted.printNumberOfCars]<br>Current Transaction: com.youlearncode.transactionalAnnotation.isolation.CarRepositoryReadUncommitted.printNumberOfCars<br>Is active? true<br>Number of cars in db: 2<br>2023-06-24T22:14:39.406+03:00 TRACE 17236 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Completing transaction for [com.youlearncode.transactionalAnnotation.isolation.CarRepositoryReadUncommitted.printNumberOfCars]<br>2023-06-24T22:14:39.406+03:00 TRACE 17236 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Completing transaction for [com.youlearncode.transactionalAnnotation.isolation.CarRepositoryReadUncommitted.demonstrateIsolationType]</pre><h4>6.1.2 @Transactional(isolation = READ_COMMITTED)</h4><blockquote><em>Remember to change the profiles in application.properties to spring.profiles.active=isolation,readcommited</em></blockquote><p>The READ_COMMITTED is the default option, and if you do use this option, the transaction will only read data from committed transactions. This means that dirty reads will not happen, while non-repeatable reads and phantom reads can happen.</p><p>As a result, if we change the above class to this:</p><pre>package com.youlearncode.transactionalAnnotation.isolation;<br><br>import com.youlearncode.transactionalAnnotation.AbstractCarRepository;<br>import com.youlearncode.transactionalAnnotation.Car;<br>import com.youlearncode.transactionalAnnotation.isolation.setup.repository.CarRepository;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.ApplicationContext;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.jdbc.core.SingleColumnRowMapper;<br>import org.springframework.stereotype.Repository;<br>import org.springframework.transaction.annotation.Isolation;<br>import org.springframework.transaction.annotation.Propagation;<br>import org.springframework.transaction.annotation.Transactional;<br>import org.springframework.transaction.support.TransactionSynchronizationManager;<br><br>@Repository<br>@Profile(&quot;readcommitted &amp; isolation&quot;)<br>public class CarRepositoryReadCommitted extends AbstractCarRepository implements CarRepository {<br><br>    @Autowired<br>    public CarRepositoryReadCommitted(JdbcTemplate jdbcTemplate, ApplicationContext applicationContext) {<br>        super(jdbcTemplate, applicationContext);<br>    }<br><br>    @Transactional<br>    public void demonstrateIsolationType(Car car) throws Exception {<br>        jdbcTemplate.update(<br>                &quot;INSERT INTO car(id, model, brand, horsepower, price) values (?,?,?,?,?)&quot;,<br>                car.getId(), car.getModel(), car.getBrand(), car.getHorsePower(), car.getPrice()<br>        );<br>        var bean = applicationContext.getBean(&quot;carRepositoryReadCommitted&quot;, CarRepositoryReadCommitted.class);<br>        bean.printNumberOfCars();<br>    }<br><br>    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRES_NEW)<br>    public void printNumberOfCars() throws Exception {<br>        System.out.println(&quot;Current Transaction: &quot; + TransactionSynchronizationManager.getCurrentTransactionName());<br>        System.out.println(&quot;Is active? &quot; + TransactionSynchronizationManager.isActualTransactionActive());<br>        var count = jdbcTemplate.queryForObject(&quot;select count(id) from car&quot;, new SingleColumnRowMapper&lt;&gt;());<br>        System.out.println(&quot;Number of cars in db: &quot; + count);<br>    }<br>    <br>}</pre><p>Since the first transaction would have not been committed when bean.printNumberOfCars is called, we will see that only one car will be found as a result of the select count(id) from car.</p><h3>6.2 @Transactional REPEATABLE_READ &amp; SERIALIZABLE Levels</h3><blockquote><em>Remember to change the profiles in application.properties to spring.profiles.active=isolation,reapeatableread</em></blockquote><p><strong>With this isolation level, both dirty reads and non-repeatable reads are prevented, while phantom reads can still happen.</strong></p><p>Now let’s use the following class:</p><pre>package com.youlearncode.transactionalAnnotation.isolation;<br><br>import com.youlearncode.transactionalAnnotation.AbstractCarRepository;<br>import com.youlearncode.transactionalAnnotation.Car;<br>import com.youlearncode.transactionalAnnotation.isolation.setup.repository.CarRepository;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.ApplicationContext;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.jdbc.core.SingleColumnRowMapper;<br>import org.springframework.stereotype.Repository;<br>import org.springframework.transaction.annotation.Isolation;<br>import org.springframework.transaction.annotation.Propagation;<br>import org.springframework.transaction.annotation.Transactional;<br>import org.springframework.transaction.support.TransactionSynchronizationManager;<br><br>@Repository<br>@Profile(&quot;repeatableread &amp; isolation&quot;)<br>public class CarRepositoryRepeatableRead extends AbstractCarRepository implements CarRepository {<br><br>    @Autowired<br>    public CarRepositoryRepeatableRead(JdbcTemplate jdbcTemplate, ApplicationContext applicationContext) {<br>        super(jdbcTemplate, applicationContext);<br>    }<br><br>    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ)<br>    public void demonstrateIsolationType(Car car) throws Exception {<br>        jdbcTemplate.update(<br>                &quot;INSERT INTO car(id, model, brand, horsepower, price) values (?,?,?,?,?)&quot;,<br>                car.getId(), car.getModel(), car.getBrand(), car.getHorsePower(), car.getPrice()<br>        );<br>        var priceBefore = jdbcTemplate.queryForObject(&quot;select price from car where id = 1&quot;, new SingleColumnRowMapper&lt;&gt;());<br>        System.out.println(&quot;Price of first  before: &quot; + priceBefore);<br>        var bean = applicationContext.getBean(&quot;carRepositoryRepeatableRead&quot;, CarRepositoryRepeatableRead.class);<br><br>        new Thread(() -&gt; {<br>            try {<br>                bean.countCarsAndUpdateTheExisting();<br>            } catch (Exception e) {<br>                throw new RuntimeException(e);<br>            }<br>        }).start();<br><br>        Thread.sleep(1000);<br>        var priceAfter = jdbcTemplate.queryForObject(&quot;select price from car where id = 1&quot;, new SingleColumnRowMapper&lt;&gt;());<br><br>        System.out.println(&quot;Price of first  after: &quot; + priceAfter);<br><br>    }<br><br>    @Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_UNCOMMITTED)<br>    public void countCarsAndUpdateTheExisting() throws Exception {<br>        System.out.println(&quot;Current Transaction: &quot; + TransactionSynchronizationManager.getCurrentTransactionName());<br>        System.out.println(&quot;Is active? &quot; + TransactionSynchronizationManager.isActualTransactionActive());<br>        var count = jdbcTemplate.queryForObject(&quot;select count(id) from car&quot;, new SingleColumnRowMapper&lt;&gt;());<br>        System.out.println(&quot;Number of cars in db: &quot; + count);<br>        jdbcTemplate.update(&quot;UPDATE car set price = 22000 where id = 1&quot;);<br>    }<br><br><br>}</pre><p>Now let’s see what happens here if we send the same request as before:</p><pre>2023-06-24T22:29:45.557+03:00 TRACE 5720 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Getting transaction for [com.youlearncode.transactionalAnnotation.isolation.CarRepositoryRepeatableRead.demonstrateIsolationType]<br>Price of first  before: 20000.0<br>2023-06-24T22:29:45.580+03:00 TRACE 5720 --- [       Thread-1] o.s.t.i.TransactionInterceptor           : Getting transaction for [com.youlearncode.transactionalAnnotation.isolation.CarRepositoryRepeatableRead.countCarsAndUpdateTheExisting]<br>2023-06-24T22:29:45.583+03:00 TRACE 5720 --- [       Thread-1] o.s.t.i.TransactionInterceptor           : Completing transaction for [com.youlearncode.transactionalAnnotation.isolation.CarRepositoryRepeatableRead.countCarsAndUpdateTheExisting]<br>Price of first  after: 20000.0<br>2023-06-24T22:29:46.584+03:00 TRACE 5720 --- [nio-8080-exec-1] o.s.t.i.TransactionInterceptor           : Completing transaction for [com.youlearncode.transactionalAnnotation.isolation.CarRepositoryRepeatableRead.demonstrateIsolationType]</pre><p>Firstly, the new car was inserted and the price of the first car that was in the database was retrieved($20,000). Then we call the other transactional method, which will update the price of the car. <strong>Note that since we have chosen the REPEATABLE_READ isolation option, the data that the first transaction reads will be unchanged</strong>. As a result, the price that we retrieve after the update will not change.</p><p>Should you try to change the REPEATABLE_READ to READ_COMMITTED or READ_UNCOMMITTED, you will see that the last print statement will return the updated price($22000).</p><p>Last but not least, <strong>the SERIALIZABLE isolation level is the only level where neither dirty reads nor non-repeatable reads nor phantom reads can happen</strong>.</p><h3>7. @Transactional RollbackFor &amp; NoRollbackFor Attributes</h3><p>In this section, we will see how we can modify the attributes that have to do with when the transaction should and when it should not rollback.</p><p>Before we begin, create a new package named rollback, under that a package named setup, and just like before, three classes under that:</p><p><strong>RestController.java</strong></p><pre>package com.youlearncode.transactionalAnnotation.rollback.setup.controller;<br><br>import com.youlearncode.transactionalAnnotation.Car;<br>import com.youlearncode.transactionalAnnotation.rollback.setup.service.CarService;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.http.MediaType;<br>import org.springframework.web.bind.annotation.PostMapping;<br>import org.springframework.web.bind.annotation.RequestBody;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>/**<br> * Rest Controller for cars<br> */<br>@RestController<br>@RequestMapping(value = &quot;/cars&quot;, produces = MediaType.APPLICATION_JSON_VALUE)<br>@Profile(&quot;rollback&quot;)<br>public class CarRestController {<br><br>    private final CarService carService;<br><br>    @Autowired<br>    public CarRestController(CarService carService) {<br>        this.carService = carService;<br>    }<br><br><br>    @PostMapping<br>    public void addCar(@RequestBody Car car) throws Exception{<br>        carService.demonstrateRollback(car);<br>    }<br><br>}</pre><p><strong>CarRepository.java</strong></p><pre>package com.youlearncode.transactionalAnnotation.rollback.setup.repository;<br><br><br>import com.youlearncode.transactionalAnnotation.Car;<br><br>public interface CarRepository {<br><br>    void demonstrateRollback(Car car) throws Exception;<br><br>}</pre><p>and finally, the <strong>CarService.java</strong>:</p><pre>package com.youlearncode.transactionalAnnotation.rollback.setup.service;<br><br>import com.youlearncode.transactionalAnnotation.Car;<br>import com.youlearncode.transactionalAnnotation.rollback.setup.repository.CarRepository;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>@Profile(&quot;rollback&quot;)<br>public class CarService {<br><br>    private final CarRepository carRepository;<br><br>    public CarService(CarRepository carRepository) {<br>        this.carRepository = carRepository;<br>    }<br>    <br>    public void demonstrateRollback(Car car) throws Exception {<br>        carRepository.demonstrateRollback(car);<br>    }<br>}</pre><h3>7.1 Default RollbackFor Option</h3><blockquote><em>Remember to change the profiles to this: spring.profiles.active=rollback,defaultrollback</em></blockquote><p>By default, a transaction will roll back if any RuntimeException or Error is thrown. This means that if a checked exception(e.g. IOException) is thrown, the transaction will NOT rollback.</p><p>Now consider the following example:</p><pre>package com.youlearncode.transactionalAnnotation.rollback;<br><br>import com.youlearncode.transactionalAnnotation.AbstractCarRepository;<br>import com.youlearncode.transactionalAnnotation.Car;<br>import com.youlearncode.transactionalAnnotation.rollback.setup.CarRepository;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.ApplicationContext;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.stereotype.Repository;<br>import org.springframework.transaction.annotation.Transactional;<br><br>@Repository<br>@Profile(&quot;rollback &amp; norollbackfor&quot;)<br>public class CarRepositoryNoRollbackFor extends AbstractCarRepository implements CarRepository {<br><br>    @Autowired<br>    public CarRepositoryNoRollbackFor(JdbcTemplate jdbcTemplate, ApplicationContext applicationContext) {<br>        super(jdbcTemplate, applicationContext);<br>    }<br><br>    @Transactional(noRollbackFor = NullPointerException.class)<br>    public void demonstrateRollback(Car car) {<br>        jdbcTemplate.update(<br>                &quot;INSERT INTO car(model, brand, horsepower, price) values (?,?,?,?)&quot;,<br>                car.getModel(), car.getBrand(), car.getHorsePower(), car.getPrice()<br>        );<br>        throw new NullPointerException(&quot;Null Pointer Exception&quot;);<br><br>    }<br>    <br>}</pre><p>Of course, if you add any car, the insertion will rollback, and the only car that will be found in the database is the one that was inserted on startup.</p><p>However, if we change the NullPointer exception to IOException and just added it to the signature( throws IOException), the number of cars in the database will be two.</p><h3>7.2 RollbackFor Attribute</h3><blockquote><em>Remember to change the profiles to this: spring.profiles.active=rollback,rollbackfor</em></blockquote><p>If you do want the transaction to rollback when a checked exception is thrown, you can use the rollbackFor attribute as shown below, to make sure that the transaction will rollback should a type of exception is thrown:</p><pre>package com.youlearncode.transactionalAnnotation.rollback;<br><br>import com.youlearncode.transactionalAnnotation.AbstractCarRepository;<br>import com.youlearncode.transactionalAnnotation.Car;<br>import com.youlearncode.transactionalAnnotation.rollback.setup.CarRepository;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.ApplicationContext;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.stereotype.Repository;<br>import org.springframework.transaction.annotation.Transactional;<br><br>import java.io.FileNotFoundException;<br><br>@Repository<br>@Profile(&quot;rollback &amp; rollbackfor&quot;)<br>public class CarRepositoryRollbackFor extends AbstractCarRepository implements CarRepository {<br><br><br>    @Autowired<br>    public CarRepositoryRollbackFor(JdbcTemplate jdbcTemplate, ApplicationContext applicationContext) {<br>        super(jdbcTemplate, applicationContext);<br>    }<br><br>    @Transactional(rollbackFor = FileNotFoundException.class)<br>    public void demonstrateRollback(Car car) throws FileNotFoundException {<br>        jdbcTemplate.update(<br>                &quot;INSERT INTO car(model, b&quot; +<br>                        &quot;rand, horsepower, price) values (?,?,?,?)&quot;,<br>                car.getModel(), car.getBrand(), car.getHorsePower(), car.getPrice()<br>        );<br>        throw new FileNotFoundException(&quot;Just an iob exception&quot;);<br><br>    }<br>    <br>}</pre><p>In this case, the transaction will rollback and no new car will be inserted.</p><p>Last but not least, you can add multiple types of exceptions like this:</p><pre>@Transactional(rollbackFor = {FileNotFoundException.class, InterruptedIOException.class} )</pre><h3>7.3 NoRollbackFor Attribute</h3><blockquote><em>Remember to change the profiles to this: spring.profiles.active=rollback,norollbackfor</em></blockquote><p>If you do want the transaction to not rollback when a runtime or error is thrown, you can use the noRollbackFor attribute as shown below:</p><pre>package com.youlearncode.transactionalAnnotation.rollback;<br><br>import com.youlearncode.transactionalAnnotation.AbstractCarRepository;<br>import com.youlearncode.transactionalAnnotation.Car;<br>import com.youlearncode.transactionalAnnotation.rollback.setup.CarRepository;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.ApplicationContext;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.stereotype.Repository;<br>import org.springframework.transaction.annotation.Transactional;<br><br>@Repository<br>@Profile(&quot;rollback &amp; norollbackfor&quot;)<br>public class CarRepositoryNoRollbackFor extends AbstractCarRepository implements CarRepository {<br><br>    @Autowired<br>    public CarRepositoryNoRollbackFor(JdbcTemplate jdbcTemplate, ApplicationContext applicationContext) {<br>        super(jdbcTemplate, applicationContext);<br>    }<br><br>    @Transactional(noRollbackFor = NullPointerException.class)<br>    public void demonstrateRollback(Car car) {<br>        jdbcTemplate.update(<br>                &quot;INSERT INTO car(model, brand, horsepower, price) values (?,?,?,?)&quot;,<br>                car.getModel(), car.getBrand(), car.getHorsePower(), car.getPrice()<br>        );<br>        throw new NullPointerException(&quot;Null Pointer Exception&quot;);<br><br>    }<br>}</pre><p>In this case, the transaction will not rollback and the new car will be inserted as expected.</p><p>Just like with rollbackFor, you can add multiple types of exceptions like this:</p><pre>@Transactional(noRollbackFor = {NullPointerException.class, IndexOutOfBoundsException.class} )</pre><h3>8. Conclusion</h3><p>Having read about @Transactional annotation, you will be able to use the most complex attributes such as propagation and isolation while knowing how they work and when you should choose another propagation type or isolation level. You can find the source code on my <a href="https://github.com/geonikpal/youlearncode-tutorials/tree/transactional-annotation">GitHub page</a>.</p><h3>9. Sources</h3><p><strong>[1]</strong>: <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/transaction/annotation/Transactional.html">Transactional (Spring Framework 6.0.10 API) <em>— Spring Docs</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23c6ffc4ee7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Bean Scopes]]></title>
            <link>https://medium.com/@geonikpal/spring-bean-scopes-70ed7cbc97c9?source=rss-a724af3d3d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/70ed7cbc97c9</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-bean]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Georgios Nikolaos Palaiologopoulos]]></dc:creator>
            <pubDate>Thu, 30 Mar 2023 20:00:11 GMT</pubDate>
            <atom:updated>2024-12-14T16:24:48.522Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’ll talk about Spring Bean Scopes, through detailed examples.</p><h3>1. What are Spring Bean Scopes?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yvwluuw4tmaNP3FBO-2Q_Q.png" /></figure><p>Spring Bean Scopes provide us with the ability to finely control the creation of bean instances. While we may choose to create certain bean instances as singletons or prototypes, we may want others to be created either per request or once per session.</p><p>To define the Scope of a bean, you have to use the @Scope annotation, either on the type level or method level. The possible scopes are the following:</p><ul><li>singleton (this is the default one)</li><li>prototype</li><li>request (can be used only with spring-boot-web)</li><li>session (can be used only with spring-boot-web)</li><li>application (can be used only with spring-boot-web)</li><li>websocket (can be used only with spring-boot-websocket)</li></ul><p>In the following sections, we will take a deep look at how @Scope annotation works and learn about all four possible scope options.</p><h3>2. Setting Up the Project</h3><p>For this tutorial, we are using the <strong>IntelliJ IDEA Community edition</strong> which you can download <a href="https://www.jetbrains.com/idea/download/">here</a>.</p><p>If you are not using this IDE, you also need to download Maven <a href="https://maven.apache.org/download.cgi">here</a>.</p><p>The next step is to visit <a href="https://start.spring.io/">Spring initializr</a> and generate a project according to these settings shown in the image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x8UkSGx3U2YsdXxU.png" /></figure><p>After having chosen the above options, press the GENERATE button, and a new spring boot project will be downloaded for you. Then you have to unzip the compressed archive and open the folder with your favorite IDE.</p><h3>3. The @Scope Annotation</h3><p>The @Scope annotation can be either applied to types(@Component, @Service, etc. annotated classes) or methods(@Bean annotated methods). Moreover, it has the following attributes:</p><ul><li>value - The name of the scope for this bean, must be either empty or one of the possible scopes that we described in the first section</li><li>scopeName - an alias for the above</li><li>proxyMode - It defines if a component should be set as a scoped proxy, it defaults to ScopedProxyMode.DEFAULT and it can have the following values:<br>- ScopedProxyMode.<em>DEFAULT</em> - Usually is NO, unless we have configured it otherwise at the component-scan level<br>- ScopedProxyMode.<em>NO</em> - Usually used with Singleton scope<br>- ScopedProxyMode.<em>INTERFACES</em> - Creates a JDK dynamic proxy that implements all interfaces exposed by the class of the target object<br>- ScopedProxyMode.<em>TARGET_CLASS</em> - Creates a class-based proxy (CGLIB)</li></ul><h3>4. Singleton Scope</h3><p>This is the default scope of Spring, and it means that when a Spring component is injected,<strong> the spring bean will only be created once</strong>.</p><p>Consider that we have the following example where we have a simple component and service as shown below :</p><pre>import org.springframework.stereotype.Component;<br>@Component<br>public class Singleton {}</pre><pre>@Service<br>public class ServiceForSingleton {<br><br>    private final Singleton singleton1;<br>    private final Singleton singleton2;<br><br>    public Service(Singleton singleton1, Singleton singleton2) {<br>        this.singleton1 = singleton1;<br>        this.singleton2 = singleton2;<br>        System.out.println(singleton1);<br>        System.out.println(singleton2);<br>    }<br>}</pre><p>Now if you do run the app, even though you have 2 singleton objects, you will see the following:</p><pre>com.youlearncode.springBeanScopes.scopes.nonWeb.singleton.Singleton@1e7ab390<br>com.youlearncode.springBeanScopes.scopes.nonWeb.singleton.Singleton@1e7ab390</pre><p>Which means that both point to the same object.</p><p>Last but not least, if for any reason you want to explicitly define the scope as a singleton, you can accomplish it like this:</p><ul><li>@Scope(&quot;singleton&quot;) OR</li><li>@Scope(ConfigurableBeanFactory.<em>SCOPE_SINGLETON</em>)</li></ul><h3>5. Prototype Scope</h3><p>On the other hand, you can force the creation of a new Spring-managed bean each time it is injected, by using the prototype scope either like this: @Scope(ConfigurableBeanFactory.<em>SCOPE_PROTOTYPE</em>) or like this: @Scope(&quot;prototype&quot;)</p><p>For instance, if we have the following service and component:</p><pre>import org.springframework.beans.factory.config.ConfigurableBeanFactory;<br>import org.springframework.context.annotation.Scope;<br>import org.springframework.stereotype.Component;<br><br>@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)<br>@Component<br>public class Prototype {}</pre><pre>import org.springframework.stereotype.Service;<br><br>@Service<br>public class ServiceForPrototype {<br><br>    private final Prototype prototype1;<br>    private final Prototype prototype2;<br><br><br>    public ServiceForPrototype(Prototype prototype1, Prototype prototype2) {<br>        this.prototype1 = prototype1;<br>        this.prototype2 = prototype2;<br>        System.out.println(prototype1);<br>        System.out.println(prototype2);<br>    }<br>}</pre><p>and run the application, we will see two different hashcodes for the two objects, in contrast to what we saw with singleton scope:</p><pre>com.youlearncode.springBeanScopes.scopes.nonWeb.prototype.Prototype@26cb5207<br>com.youlearncode.springBeanScopes.scopes.nonWeb.prototype.Prototype@15400fff</pre><h3>6. Web Scopes</h3><p>To use the web scopes, you must have spring-boot-starter web as a dependency. In the following sections, we’ll see how every one of them works.</p><p>Note that when dealing with web scopes, we use the ScopedProxyMode.<em>TARGET_CLASS</em> proxymode because the proxy makes sure that each thread gets its own instance of the bean by delegating each call to the actual bean instance that was created by the Spring container.</p><h3>6.1 Request Scope</h3><p>You can set the scope of a bean to be per request by using one the following three ways:</p><ul><li>@Scope(scopeName = WebApplicationContext.<em>SCOPE_REQUEST</em>, proxyMode = ScopedProxyMode.<em>TARGET_CLASS</em>)</li><li>@RequestScope - it&#39;s exactly like the above</li></ul><p>Now consider the following example with just a controller and a component:</p><pre>import org.springframework.http.MediaType;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>@RequestMapping(value = &quot;/hello&quot;, produces = MediaType.APPLICATION_JSON_VALUE)<br>public class HelloController {<br><br>    private final RequestScopeBean requestScopeBean;<br><br>    public HelloController(RequestScopeBean requestScopeBean) {<br>        this.requestScopeBean = requestScopeBean;<br>    }<br><br><br>    @GetMapping<br>    public String getAll() {<br>        System.out.println(&quot;RequestScopeBean: &quot;+requestScopeBean);<br>        return &quot;Hello&quot;;<br>    }<br>}</pre><pre>import org.springframework.stereotype.Service;<br>import org.springframework.web.context.annotation.RequestScope;<br><br>@Component<br>@RequestScope<br>public class RequestScopeBean {<br>    @PreDestroy<br>    public void preDestroy(){<br>        System.out.println(&quot;Destroying bean: &quot;+ this);<br>    }<br>}</pre><p>Note that we also added the @PreDestroy annotation to print just before the destruction of the bean.</p><p>Going forward, if you want to understand how this works, you can start the application and go to <a href="http://localhost:8080/hello">http://localhost:8080/hello</a>. Then, you can press refresh another two times and you will see the following logs:</p><pre>RequestScopeBean: com.youlearncode.springBeanScopes.scopes.web.RequestScopeBean@3de2dd29<br>Destroying bean: com.youlearncode.springBeanScopes.scopes.web.RequestScopeBean@3de2dd29<br>RequestScopeBean: com.youlearncode.springBeanScopes.scopes.web.RequestScopeBean@b739854<br>Destroying bean: com.youlearncode.springBeanScopes.scopes.web.RequestScopeBean@b739854<br>RequestScopeBean: com.youlearncode.springBeanScopes.scopes.web.RequestScopeBean@5fcb5753</pre><p>As you can infer, every time you sent a GET request, the previous bean was destroyed while a new one was created. Of course, if you remove the @RequestScope annotation the bean will just be a singleton.</p><h3>6.2 Session Scope</h3><p>The logic with session scope is pretty similar to request scope but the life of a bean depends on the session. Just like with @RequestScope, you just have to add the annotation @SessionScope.</p><p>So let’s create a new bean and inject into the previous controller that we had created:</p><pre>import jakarta.annotation.PreDestroy;<br>import org.springframework.stereotype.Service;<br>import org.springframework.web.context.annotation.SessionScope;<br><br>@Service<br>@SessionScope<br>public class SessionScopeBean {<br><br>    @PreDestroy<br>    public void preDestroy(){<br>        System.out.println(&quot;Destroying bean: &quot;+ this);<br>    }<br>}</pre><p>and the controller will look like this:</p><pre>import org.springframework.http.MediaType;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>@RequestMapping(value = &quot;/hello&quot;, produces = MediaType.APPLICATION_JSON_VALUE)<br>public class HelloController {<br><br>    private RequestScopeBean requestScopeBean;<br>    private SessionScopeBean sessionScopeBean;<br><br>    public HelloController(RequestScopeBean requestScopeBean, SessionScopeBean sessionScopeBean) {<br>        this.requestScopeBean = requestScopeBean;<br>        this.sessionScopeBean = sessionScopeBean;<br>    }<br><br><br>    @GetMapping<br>    public String getAll() {<br>        System.out.println(&quot;RequestScopeBean: &quot;+requestScopeBean);<br>        System.out.println(&quot;SessionScopeBean: &quot;+sessionScopeBean);<br>        return &quot;Hello&quot;;<br>    }<br>}</pre><p>Now you can restart the application and press F5 many times; you will see the bean’s hashcode is the same. To trigger the creation of a new bean you can try to end the session by pressing F12 -&gt; Application, then delete the cookie JSESSIONID and if you press F5 again, you will see the hashcode will be different.</p><p>Last but not least, note that in this case the bean will not be destroyed, and this happens because the session-scoped beans are not destroyed by the Spring container, but by the servlet container.</p><h3>6.3 Application Scope</h3><p>As for the application scope, it is used to define that a bean will be created once per application context. Moreover, to set the scope of a bean as application, you should write the @ApplicationScope annotation at method or type level.</p><h3>7. WebSocket Scope</h3><p>The last scope that we will investigate is the websocket scope and in order to use it, you must have spring-boot-starter-websocket included.</p><p>As the name implies, the scope of a bean will be per websocket session, so for every websocket session we open, a new bean will be created.</p><p>To see that in action, we have to create a WebSocketConfig class in order to enable websocket and register the endpoints:</p><pre>import org.springframework.context.annotation.Configuration;<br>import org.springframework.messaging.simp.config.MessageBrokerRegistry;<br>import org.springframework.web.socket.config.annotation.EnableWebSocket;<br>import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;<br>import org.springframework.web.socket.config.annotation.StompEndpointRegistry;<br>import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;<br><br>@Configuration<br>@EnableWebSocket<br>@EnableWebSocketMessageBroker<br>public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {<br><br>    @Override<br>    public void configureMessageBroker(MessageBrokerRegistry config) {<br>        config.enableSimpleBroker(&quot;/topic&quot;);<br>        config.setApplicationDestinationPrefixes(&quot;/app&quot;);<br>    }<br><br>    @Override<br>    public void registerStompEndpoints(StompEndpointRegistry registry) {<br>         registry.addEndpoint(&quot;/youlearncode&quot;)<br>                 .setAllowedOriginPatterns(&quot;*&quot;)<br>                 .withSockJS();<br>    }<br>}</pre><p>Then we must create a bean as shown below:</p><pre>@Component<br>@Scope(scopeName = &quot;websocket&quot;, proxyMode = ScopedProxyMode.TARGET_CLASS)<br>public class PerWebSocketConnectionBean {<br><br>    @PreDestroy<br>    public void destroy(){<br>        System.out.println(&quot;destroying bean: &quot; + this);<br>    }<br>}</pre><p>and a controller in order to specify the endpoint of our message:</p><pre>import org.springframework.messaging.handler.annotation.MessageMapping;<br>import org.springframework.messaging.handler.annotation.SendTo;<br><br>@org.springframework.stereotype.Controller<br>public class Controller {<br><br>    private final PerWebSocketConnectionBean perWebSocketConnectionBean;<br><br>    public Controller(PerWebSocketConnectionBean perWebSocketConnectionBean) {<br>        this.myBean = perWebSocketConnectionBean;<br>    }<br><br>    @MessageMapping(&quot;/youlearncode&quot;)<br>    @SendTo(&quot;/topic/messages&quot;)<br>    public String send(String message) throws Exception {<br>        System.out.println(perWebSocketConnectionBean);<br>        return message;<br>    }<br>}</pre><p>Finally, we have to create the websocket client as shown below:</p><pre>&lt;html&gt;<br>    &lt;head&gt;<br>        &lt;title&gt;Websocket Scope Test&lt;/title&gt;<br>        &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.6.1/sockjs.min.js&quot;&gt;&lt;/script&gt;<br>        &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;&lt;/body&gt;<br>    &lt;script&gt;<br>    let socket = new SockJS(&#39;http://localhost:8080/youlearncode&#39;);<br>    let stompClient = Stomp.over(socket);  <br>    stompClient.connect({}, function(frame) {<br>        stompClient.subscribe(&#39;/topic/messages&#39;)<br>        stompClient.send(&quot;/app/youlearncode&quot;, {}, &quot;hello&quot;);<br>    });<br>    window.addEventListener(&quot;beforeunload&quot;, function(e){<br>     stompClient.disconnect();<br>    }, false);<br>    &lt;/script&gt;<br>&lt;/html&gt;</pre><p>After having done everything, you can start the app, open the html file with your favorite browser and check the logs:</p><pre>com.youlearncode.springBeanScopes.scopes.websocket.PerWebSocketConnectionBean@76fed1d3</pre><p>If you do close the window, the client will disconnect, the bean will be destroyed and the logs will show:</p><pre>destroying bean: com.youlearncode.springBeanScopes.scopes.websocket.PerWebSocketConnectionBean@76fed1d3</pre><p>Of course, if you remove the websocket scope, the bean will not die per websocket session since the scope will be just singleton.</p><h3>8. Conclusion</h3><p>By now, you should know all the possible scopes that exist in Spring, when and why you should pick one, depending on the needs of your application. Finally, you can find the source code on my <a href="https://github.com/geonikpal/youlearncode-tutorials/tree/spring-bean-scopes">Github page</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70ed7cbc97c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Classes & Objects]]></title>
            <link>https://medium.com/@geonikpal/java-classes-objects-a255d9521850?source=rss-a724af3d3d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/a255d9521850</guid>
            <category><![CDATA[java-class]]></category>
            <category><![CDATA[core-java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-object]]></category>
            <dc:creator><![CDATA[Georgios Nikolaos Palaiologopoulos]]></dc:creator>
            <pubDate>Sun, 19 Mar 2023 18:00:29 GMT</pubDate>
            <atom:updated>2024-06-14T19:41:36.388Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bjex2EDsoL9VP8aYP5jo0A.png" /></figure><p>In this article, we’ll talk about Java Classes &amp; Objects, one of the most vital components of the Java programming language.</p><h3>1. Java Classes</h3><p>In this section, we will dig deep into Java Classes and learn everything about them.</p><h3>1.1 What is a Class in Java</h3><p>You can think of a <strong>Java class as a blueprint or a template, of how any instance created using this class will be formed</strong>. Inside a class, you can define all the information that can be held and all the functionalities that instances of this class should be able to perform.</p><p>To define a class, you must use the class keyword as shown below:</p><pre>access_modifier class className {<br><br>}</pre><p>Moreover, <strong>classes can extend(inherit) only one class but can implement multiple interfaces</strong>.</p><p>To extend a class, you just use the extends keyword as shown below:</p><pre>access_modifier class className extends parentClassName {<br><br>}</pre><p>If you want to implement interfaces, you must use the implements keyword</p><pre>access_modifier class className implements interfaceName1, interfaceName2, ..., interfaceNameN {<br><br>}</pre><p>Last but not least, you can add keywords such as final, abstract, static, sealed, etc., <strong>to restrict how classes should work</strong>. Of course, we will dig deeper in the following sections where we will learn about the types of classes that exist.</p><h3>1.2 Java Class Structure</h3><p>In this section, we will learn about all the components that a class might have.</p><h4>1.2.1 Java Class Fields</h4><p>The fields of a class are its characteristics. For example, for an employee, we might want to be able to hold information such as name, surname, and employee id, so when requested, all info can be returned as a single unit, inside an object.</p><p>An Employee class with the aforementioned characteristics could look like this:</p><pre>public class Employee {<br>    <br>    private String name;<br>    private String surname;<br>    private String employeeID;<br>}</pre><p>Of course, with this implementation, you will never be able to access or modify any Employee instance outside of this class, but we will look in the following sections at how this could be done.</p><h4>1.2.2 Java Class Constructors</h4><p>Now that we defined the blueprint of an Employee, we need to be able to create it. To create an Employee instance you must use a constructor, and unless you define your own constructors, the only one you can use, is the default with new keyword:</p><pre>Employee employee = new Employee();</pre><p>Of course, since we haven’t declared any method that could modify the instance, with the current implementation, we can only create an employee with no data. However, if we declare a constructor like this:</p><pre>public Employee(String name, String surname, String employeeID) {<br>    this.name = name;<br>    this.surname = surname;<br>    this.employeeID = employeeID;<br>}</pre><p>We will be able to create a new employee as shown below:</p><pre>Employee employee = new Employee(&quot;Georgios&quot;, &quot;Pal&quot;, &quot;HGI-87954&quot;);</pre><p>Last but not least, note that we still can’t access or modify any information of any employee object outside Employee class.</p><h4>1.2.3 Java Class Methods</h4><p>The methods of a class define the behavior of the object. When defining an entity like Employee, we should use getters(public methods that allow you to access fields of an object) and setters(public methods that allow you to modify fields of an object).</p><p>For instance, to be able to access and modify Employee objects, you should change the Employee class as shown below:</p><pre>public class Employee {<br><br>    private String name;<br>    private String surname;<br>    private String employeeID;<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public String getSurname() {<br>        return surname;<br>    }<br><br>    public void setSurname(String surname) {<br>        this.surname = surname;<br>    }<br><br>    public String getEmployeeID() {<br>        return employeeID;<br>    }<br><br>    public void setEmployeeID(String employeeID) {<br>        this.employeeID = employeeID;<br>    }<br>}</pre><p>As a result, you will be able to do the following:</p><pre>Employee employee = new Employee();<br>// Modify object<br>employee.setName(&quot;Georgios&quot;);<br>employee.setName(&quot;Pal&quot;);<br>employee.setEmployeeID(&quot;HGI-87954&quot;);<br><br>//access object<br>String name = employee.getName();<br>String surname = employee.getSurname();<br>String employeeID = employee.getEmployeeID();</pre><p>Note that there might be cases when you do not want to create setters and getters, to encapsulate information.</p><p>Now, besides getters and setters, you might want to define other methods inside a class, for example, in a class named Circle, you could define one method that calculates the area and one that calculates the perimeter of the circle:</p><pre>public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public double getArea() { return Math.PI * Math.pow(radius, 2); } public double getPerimeter() { return 2 * Math.PI * radius; } }</pre><p>Then, we will be able to create new Circle objects and call these methods and get the results:</p><pre>public class Circle {<br><br>    private double radius;<br><br>    public Circle(double radius) {<br>        this.radius = radius;<br>    }<br><br>    public double getArea() {<br>        return Math.PI * Math.pow(radius, 2);<br>    }<br><br>    public double getPerimeter() {<br>        return 2 * Math.PI * radius;<br>    }<br>    <br>}</pre><p>Finally, some other methods are usually overridden:</p><ul><li>hashCode — Returns a hash code value for the object</li><li>equals — the default implementation just checks for reference equality and may produce unwanted results — should be overridden</li><li>toString — this method is called implicitly when we print an object, unless we override it, it will print the class name along with the hexadecimal representation of the hashcode value.</li></ul><h4>1.2.4 Nested Classes, Enums, Records, and Interfaces</h4><p>We can also declare classes enums, records, or interfaces, usually when they have meaning only inside a specific class and won’t be used by other classes.</p><p>Consider the following example:</p><pre>public class Car {<br><br>    private String brand;<br>    private String model;<br>    private Engine engine;<br>    private Oldness oldness;<br>    private StartEndProductionYear startEndProductionYear;<br><br>    public Car(String brand, String model, Engine engine, Oldness oldness, StartEndProductionYear startEndProductionYear) {<br>        this.brand = brand;<br>        this.model = model;<br>        this.engine = engine;<br>        this.oldness = oldness;<br>        this.startEndProductionYear = startEndProductionYear;<br>    }<br><br>    public static class Engine {<br>        private int cc;<br>        private int horsePower;<br><br>        public Engine(int cc, int horsePower) {<br>            this.cc = cc;<br>            this.horsePower = horsePower;<br>        }<br>    }<br><br>    public enum Oldness {<br>        NEW, USED<br>    }<br><br>    public record StartEndProductionYear(int start, int end){};<br>}</pre><p>Then we can create a Car object as shown below:</p><pre>Car car =  new Car(<br>        &quot;Opel&quot;,<br>        &quot;Astra&quot;,<br>        new Car.Engine(1600, 105),<br>        Car.Oldness.NEW,<br>        new Car.StartEndProductionYear(2004, 2006)<br>);</pre><p>Moreover, you could add a nested interface and have some other classes implement it.</p><h3>1.3 How to Import a Class in Java</h3><p>To import a class, you should type the word import, along with the full path of the location of the class.</p><p>For example, if you want to import the ArrayList class, you should write:</p><pre>import java.util.ArrayList</pre><p>When it comes to user-defined classes, if two classes live in the same package, you won’t have to import them at all, for example, in the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/0*jrdR0JAeoYXw77t3.png" /></figure><p>If you want to use AccountType class inside Account class, you do not need to import it. However, if you want to use e.g. Account inside AccountRepository, you would have to write:</p><pre>import com.youlearncode.springBootJPA.model.Account;</pre><h3>1.4 Best Practices for Writing Java Classes</h3><h4>1.4.1 Naming</h4><p>The name of every class should follow the camel case pattern, with the first letter capitalized. For example, you could name a class “ Car&quot;, &quot; CarController&quot;, &quot; CarDAO &quot;.</p><h4>1.4.2 Fields</h4><p><strong>Visibility:</strong></p><p>The fields of a class should be <strong>private </strong>so that they only be accessed and modified through setters and getters. However, there are cases where you might want to use the protected access modifier so they are accessed directly by a child class.</p><p><strong>Immutability:</strong></p><p>In case the application requires that the fields do not change their value, you have three options:</p><ul><li>define the fields as final and initialize them only on object construction</li><li>use a record since all of its fields are final</li></ul><p>Of course, you could just not create any setters and at the same time, have an all-args constructor.</p><p><strong>Constants:</strong></p><p>If we want to define a constant, we must declare it as static final, in order to save memory(since it is a constant, we do only need one common version for all instances)</p><p><strong>Inheritance:</strong></p><p>You should try to make the fields reusable and move the common attributes to a higher level.</p><p>For example, if we want to have three classes: Person, Employee, and Contractor, we could do it like this:</p><pre>public class Person {<br><br>    private String name;<br>    private String surname;<br>    private String SSN;<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public String getSurname() {<br>        return surname;<br>    }<br><br>    public void setSurname(String surname) {<br>        this.surname = surname;<br>    }<br><br>    public String getSSN() {<br>        return SSN;<br>    }<br><br>    public void setSSN(String SSN) {<br>        this.SSN = SSN;<br>    }<br>}</pre><pre>public class Employee extends Person {<br><br>    private double monthlySalary;<br>    private int daysOff;<br><br>    public double getMonthlySalary() {<br>        return monthlySalary;<br>    }<br><br>    public void setMonthlySalary(double monthlySalary) {<br>        this.monthlySalary = monthlySalary;<br>    }<br><br>    public int getDaysOff() {<br>        return daysOff;<br>    }<br><br>    public void setDaysOff(int daysOff) {<br>        this.daysOff = daysOff;<br>    }<br>}</pre><pre>public class Contractor extends Person {<br><br>    private double hourlyPayment;<br>    private int durationOfContractInMonths;<br><br>    public double getHourlyPayment() {<br>        return hourlyPayment;<br>    }<br><br>    public void setHourlyPayment(double hourlyPayment) {<br>        this.hourlyPayment = hourlyPayment;<br>    }<br><br>    public int getDurationOfContractInMonths() {<br>        return durationOfContractInMonths;<br>    }<br><br>    public void setDurationOfContractInMonths(int durationOfContractInMonths) {<br>        this.durationOfContractInMonths = durationOfContractInMonths;<br>    }<br>}</pre><p>Hadn’t we used this pattern, we would have had to write the common attributes on both Employee and Contractor.</p><h4>1.4.3 Constructors</h4><p>When it comes to constructors, we should have proper naming for the arguments, ideally, the name of each attribute, like this:</p><pre>public Person(String name, String surname, String SSN) {<br>    this.name = name;<br>    this.surname = surname;<br>    this.SSN = SSN;<br>}</pre><p>Furthermore, we should try to reuse the constructors that we have already created, by using the this keyword:</p><pre>public Person(String name, String surname, String SSN) {<br>    this(name, surname);<br>    this.SSN = SSN;<br>}<br><br>public Person(String name, String surname) {<br>    this.name = name;<br>    this.surname = surname;<br>}</pre><h4>1.4.4 Methods</h4><p>As for methods, you should take advantage of <strong>method overloading and overriding</strong>, in order to enhance the readability and maintainability of code.</p><p><strong>Method overloading is having methods with the same name but different number and/or type of arguments</strong>. Whereas, <strong>Method overriding is when a child class or class that implements an interface, “ignores” the previous implementation and defines a new one</strong>.</p><p>Moreover, we should always move methods that are common for the children classes, inside the parent class.</p><p>Last but not least, you should define methods with the most appropriate keywords:</p><ul><li>public if it needs to be accessed from anywhere</li><li>protected if it needs to be accessed only by subclasses or classes in the same package</li><li>default(no keyword) if it needs to be accessed by classes in the same package</li><li>private if only methods inside the class should use it</li><li>final, if a method should never be overridden</li><li>static , when:<br>- these methods belong in a Utility class<br>- implementing the Singleton Design Pattern<br>- it makes sense to be able to call this method without having created any instances</li><li>synchronized, when in need of synchronization at method-level</li></ul><h3>1.5 Java Class Types</h3><p>There are many types of classes that are a more restricted version of a normal class. In this section, we will take a brief look at each of them.</p><h4>1.5.1 Abstract Classes</h4><p>Abstract classes are meant to provide partial abstraction, as they can have both abstract and non-abstract methods. Moreover, abstract classes may have constructors but you will never be able to instantiate one.</p><h4>1.5.2 Final Classes</h4><p>Final classes cannot have any descendants. In other words, by adding the final keyword when declaring a class, you will never be able to extend it.</p><p>Learn more about the final keyword in <a href="https://medium.com/@geonikpal/final-keyword-in-java-10dab7f9218a">Final Keyword in Java</a>.</p><h4>1.5.3 Sealed Classes</h4><p>In JDK 17, sealed classes were added, and they provide a way to restrict which classes can extend other classes.</p><p>You can get a deep understanding of how they work by reading Java Sealed Class &amp; Interface.</p><h4>1.5.4 Nested Static Classes &amp; Nested Non-Static(Inner) Classes</h4><p>As we saw in the previous sections, we can have classes inside classes. These classes can be categorized into two: static and non-static.</p><p>If you create a <strong>nested static class</strong>, you won’t have to have already created an object of the outer class:</p><pre>public class OuterClass {<br>    <br>    public static class NestedClass{}<br><br>}</pre><p>Then, in another class, you could do the following:</p><pre>OuterClass.NestedClass nestedClass = new OuterClass.NestedClass();</pre><p>On the other hand, if you declare the nested class as non-static, to create an instance of the nested class, you would have to first create an object of the OuterClass and then use it to create an object of the NestedClass:</p><pre>OuterClass outerClass = new OuterClass();<br>OuterClass.NestedClass = outerClass.new NestedClass();</pre><h4>1.5.5 Enums</h4><p>Enum is a special type of class and in order to create one, you type the enum keyword instead of the class and it is used mainly when the instance of a class will have specific values.</p><p>For example, an enum could be the day of the week, where there are only 7 possible values:</p><pre>public enum Day {<br>    MONDAY,<br>    TUESDAY,<br>    WEDNESDAY,<br>    THURSDAY,<br>    FRIDAY,<br>    SATURDAY,<br>    SUNDAY;<br>} </pre><p>By using the following commands:</p><pre>javac Day.java<br>javap Day.class</pre><p>We can see that under the hood, it is a final class that extends the Enum class:</p><pre>$ javap Day.class<br>Compiled from &quot;Day.java&quot;<br>public final class Day extends java.lang.Enum&lt;Day&gt; {<br>  public static final Day MONDAY;<br>  public static final Day TUESDAY;<br>  public static final Day WEDNESDAY;<br>  public static final Day THURSDAY;<br>  public static final Day FRIDAY;<br>  public static final Day SATURDAY;<br>  public static final Day SUNDAY;<br>  public static Day[] values();<br>  public static Day valueOf(java.lang.String);<br>  static {};<br>}</pre><h4>1.5.6 Records</h4><p>Java Record is another special type of class, that is final, all of its members are final. Additionally, unlike any other class that you might create, getters, equals, hashCode, and toString are implemented without the need to do it yourself.</p><p>Delve more into Records by reading <a href="https://youlearncode.com/java-record/">Java Record</a>.</p><h3>1.6 Inheritance in Java Classes</h3><p>As Java is an OOP language, it supports inheritance, and more specifically:</p><ul><li>Inheritance between classes using the extends keyword</li><li>Inheritance between classes and interfaces using the implements keyword</li></ul><p>Furthermore, as we said in section 1.1, a class can only extend one class, but it can implement one or more interfaces.</p><h3>2. Java Objects</h3><p>In this section, we will take a deeper look at Java Objects</p><h3>2.1 What is an Object in Java</h3><p>An <strong>object is nothing more than an instance of a class</strong>. As we saw in the previous section, the class is just the blueprint and the object is the actual implementation of the blueprint.</p><p>For example, let’s say that we have a class Student:</p><pre>public class Student {<br><br>    private String name;<br>    private String surname;<br>    private double averageGrade;<br><br>    public Student(String name, String surname, double averageGrade) {<br>        this.name = name;<br>        this.surname = surname;<br>        this.averageGrade = averageGrade;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public String getSurname() {<br>        return surname;<br>    }<br><br>    public void setSurname(String surname) {<br>        this.surname = surname;<br>    }<br><br>    public double getAverageGrade() {<br>        return averageGrade;<br>    }<br><br>    public void setAverageGrade(double averageGrade) {<br>        this.averageGrade = averageGrade;<br>    }<br><br>    public void study() {<br>        System.out.println(&quot;Studying...&quot;);<br>    }<br>    <br>    public void skipClass() {<br>        System.out.println(&quot;Class is boring, skipping...&quot;);<br>    }<br><br><br>}</pre><p>Now we can use this blueprint, to create actual objects with values by using the new keyword:</p><pre>// Create two students using constructors<br>Student george = new Student(&quot;Geo&quot;, &quot;Pal&quot;, 88);<br>Student nick = new Student(&quot;Nick&quot;, &quot;Pal&quot;, 80);<br>// Create another using empty constructors + setters<br>Student mau = new Student();<br>mau.setName(&quot;Mau&quot;);<br>mau.setSurname(&quot;Ave&quot;);<br>mau.setAverageGrade(90);<br><br>george.skipClass();<br><br>nick.study();<br><br>mau.study();</pre><p>The output of the above would be:</p><pre>Class is boring for Geo, skipping... Nick is Studying... Mau is Studying...</pre><h3>2.2 How to Create an Object in Java</h3><p>There are many ways to create an object in Java, with the most prominent being the new keyword, that we described in the previous section.</p><p>Nevertheless, there are other ways to create one.</p><p><strong>Creating an Object using Object.clone()</strong>:</p><p>Consider the following class:</p><pre>public class Food implements Cloneable {<br><br>    private String name;<br>    private Amount amount;<br>    private boolean glutenFree;<br><br>    public Food() {<br>    }<br><br>    public Food(String name, Amount amount, boolean glutenFree) {<br>        this.name = name;<br>        this.amount = amount;<br>        this.glutenFree = glutenFree;<br>    }<br><br>    public Amount getAmount() {<br>        return amount;<br>    }<br><br>    private static class Amount {<br>        private double number;<br>        private String metric;<br><br>        public Amount(double number, String metric) {<br>            this.number = number;<br>            this.metric = metric;<br>        }<br>    }<br>}</pre><p>In order to be able to use clone() on an object, it must implement the Cloneable interface. Moreover, clone() does a shallow copy, therefore a member that has custom-type will point to the same memory address and any change to the original object will affect the cloned.</p><p>Considering the above, if we do the following:</p><pre>Food food = new Food(&quot;Souvlaki&quot;, new Amount(300, &quot;gr&quot;), false );<br><br>Food clonedFood = (Food) food.clone();<br><br>System.out.println(clonedFood.getAmount() == food.getAmount());</pre><p>We will see that it will print true.</p><p><strong>Creating an Object using className.class.newInstance()</strong>:</p><p>This way of creating an object has been marked as deprecated since Java 9, so we will just show a brief example:</p><pre>// no-args constructor must exist since it is used by newInstance()<br>// otherwise an exception will thrown<br>Food newInstanceFood = Food.class.newInstance();<br>// the object will have name = null, amount = null, glutenFree = 0</pre><p><strong>Creating an Object using className.class.getConstructor()</strong>:</p><p>You can also create an object by using the following approach:</p><pre>Constructor&lt;Food&gt; allArgsFoodConstructor = Food.class.getConstructor(<br>        String.class,<br>        Amount.class,<br>        boolean.class<br>);<br><br>Food food = allArgsFoodConstructor.newInstance(<br>       &quot;Souvlaki&quot;,<br>       new Amount(300, &quot;gr&quot;),<br>       false<br>);</pre><p>Firstly, we retrieved the specific constructor, by providing the types of parameters and then, by using the newInstance() method, we created a new object.</p><p><strong>Creating an Object using Serialization and Deserialization</strong>:</p><p>Another way that we can use to create an object is by writing an existing object to a file and then reading from the file. To do that, we must first make Food implement Serializable and then do the following:</p><pre>// Creating the souvlaki<br>Food souvlaki = new Food(&quot;Souvlaki&quot;, new Amount(300, &quot;gr&quot;), false);<br>// Write the souvlaki to file<br>ObjectOutputStream objectOut = new ObjectOutputStream(new FileOutputStream(&quot;souvlaki.txt&quot;));<br>objectOut.writeObject(souvlaki);<br>objectOut.close();<br>// Read from the file<br>ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(&quot;souvlaki.txt&quot;));<br>// Create a new object from the file<br>Food souvlakiFromFile = (Food) objectInputStream.readObject();<br>objectInputStream.close();</pre><h3>2.3 Comparing Objects in Java</h3><p>When comparing objects of type String, or any wrapper class, the .equals method of the Object class is sufficient to produce the expected results.</p><p>However, when dealing with user-defined objects, such as the Student or Food class we examined before, the results might not be expected.</p><p>Consider that we have the Food class that we used in the previous section, if we do the following:</p><pre>Food souvlaki = new Food(&quot;Souvlaki&quot;, new Amount(300, &quot;gr&quot;), false);<br>Food souvlakiCopy = new Food(&quot;Souvlaki&quot;, new Amount(300, &quot;gr&quot;), false);<br>System.out.println(souvlaki.equals(souvlakiCopy));</pre><p>It will print false, even though the two foods are exactly the same. This happens because the equals() just compares the memory addresses of the two objects, and since we have used the new keyword, they must point to a different one.</p><p>Should you like to remedy this problem, <strong>you must override both equals and hashCode</strong>(otherwise we would violate the contract for hashCode method, that equal objects must have equal hashCodes)</p><p>Now if we just override the equals as follows:</p><pre>public class Food {<br><br>    private String name;<br>    private Amount amount;<br>    private boolean glutenFree;<br><br><br>    public Food() {<br>    }<br><br>    public Food(String name, Amount amount, boolean glutenFree) {<br>        this.name = name;<br>        this.amount = amount;<br>        this.glutenFree = glutenFree;<br>    }<br><br>    public Amount getAmount() {<br>        return amount;<br>    }<br><br>    @Override<br>    public boolean equals(Object o) {<br>        if (this == o) return true;<br>        if (!(o instanceof Food)) return false;<br>        Food food = (Food) o;<br>        return glutenFree == food.glutenFree &amp;&amp; Objects.equals(name, food.name) &amp;&amp; Objects.equals(amount, food.amount);<br>    }<br><br>//<br>//    @Override<br>//    public int hashCode() {<br>//        return Objects.hash(name, amount, glutenFree);<br>//    }<br><br>    private static class Amount {<br>        private double number;<br>        private String metric;<br><br>        public Amount(double number, String metric) {<br>            this.number = number;<br>            this.metric = metric;<br>        }<br><br>        @Override<br>        public boolean equals(Object o) {<br>            if (this == o) return true;<br>            if (!(o instanceof Amount)) return false;<br>            Amount amount = (Amount) o;<br>            return Double.compare(amount.number, number) == 0 &amp;&amp; Objects.equals(metric, amount.metric);<br>        }<br>//<br>//        @Override<br>//        public int hashCode() {<br>//            return Objects.hash(number, metric);<br>//        }<br><br>    }<br>}</pre><p>We would get true, if we rerun the same snippet.</p><p>Nevertheless, the following:</p><pre>System.out.println(souvlaki.hashCode() == souvlakiCopy.hashCode());</pre><p>Would print false, which is not the expected output, and break the contract for hashCode. Of course, if we uncomment the two hashCode implementations, it would print true, as expected.</p><h3>3. Conclusion</h3><p>After reading this article, you should know what a class is, its components, best practices, and how to make a class restricted. Moreover, you learned about what an object is, all the ways to create one, and how to compare two objects properly.</p><h3>4. Sources</h3><p>[1]: <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/classes.html">Java™ Tutorials — Classes and Objects</a> — Oracle</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a255d9521850" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Queue]]></title>
            <link>https://medium.com/@geonikpal/java-queue-0efc975a986d?source=rss-a724af3d3d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/0efc975a986d</guid>
            <category><![CDATA[core-java]]></category>
            <category><![CDATA[java-queue]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Georgios Nikolaos Palaiologopoulos]]></dc:creator>
            <pubDate>Mon, 27 Feb 2023 17:00:34 GMT</pubDate>
            <atom:updated>2024-06-23T11:00:10.183Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YQ3lwoczvqYSX9pl3KxNIQ.png" /></figure><p>In this article, we’ll go through Java Queue Interface, and how to use it.</p><h3>1. What is a Java Queue?</h3><p>A Java Queue is a <strong>FIFO</strong>(First-In-First-Out) data structure which means that the oldest item will be the first item that we will be able to remove from the queue. Moreover, as you should have already guessed, insertion order is maintained in queues.</p><p>An example of a real-life queue would be a queue at a supermarket checkout counter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8KQy4CXe53-ZduSY.png" /></figure><p>In this case, we can infer that the customers arrived at the queue in this order:</p><p>Then, each customer will pay when all customers that came before him/her have already finished the transaction.</p><p>As for the Java representation of the Queue, it is just an interface and has the following abstract methods:</p><ul><li>add(E e) - adds an element to the queue, if the queue is at capacity, it will throw an exception</li><li>offer(E e) - adds an element to the queue, does not throw an exception even if the queue is at capacity</li><li>remove() - removes the head(or the item with the highest priority) of the queue, throws exception if queue is empty</li><li>poll() - does the same as remove() but does not throw an exception if the queue is empty</li><li>element() - returns the head of the queue without removing it and it throws an exception if the queue is empty</li><li>peek() - same as element() but does not throw any exception</li></ul><p>Of course, we will see detailed examples for every method in the following sections</p><h3>2. Java Queue Example</h3><p>For this example, we will use the LinkedList implementation of Queue interface:</p><pre>Queue&lt;String&gt; queue = new LinkedList&lt;&gt;();<br><br>// Add 4 elements to the queue<br>queue.add(&quot;George&quot;);<br>queue.add(&quot;Nikolaos&quot;);<br>queue.offer(&quot;Mauricio&quot;);<br>queue.offer(&quot;Akis&quot;);<br><br>//Remove George using poll<br>String george = queue.remove();<br><br>//Remove Nikolaos using poll<br>String nikolaos = queue.poll();<br><br>//Check the head of queue using element()<br>String mauricio = queue.element();<br><br>//Remove mauricio<br>queue.remove();<br><br>//Check the head of queue using peek()<br>String akis = queue.peek();<br><br>// Remove Akis<br>queue.remove();<br><br><br>// Both of this will throw exceptions<br>// since the queue is empty<br>try {<br>    queue.remove();<br>} catch (NoSuchElementException e) {<br>    e.printStackTrace();<br>}<br><br>try {<br>    String el = queue.element();<br>} catch (NoSuchElementException e) {<br>    e.printStackTrace();<br>}</pre><p>In the example above, we added two elements using add() and two using offer(). Then we removed some elements using remove(), poll() and we checked without altering the queue by using the element() and peek(). Finally, we tried to use remove() and element() on an empty queue and saw that indeed 2 exceptions were thrown, as expected.</p><h3>3. How to Create a Queue in Java</h3><p>Since Queue is just an interface, you must choose the implementation in order to create a new Queue.</p><p>For example, you can choose LinkedList:</p><pre>Queue&lt;String&gt; cars = new LinkedList&lt;&gt;();<br>//or<br>Queue&lt;String&gt; cars = new LinkedList&lt;&gt;(Arrays.asList(&quot;Opel&quot;, &quot;VW&quot;));</pre><p>If the application requires a queue with custom priority logic and not just FIFO, you can use PriorityQueue to create a Queue:</p><pre>// Natural order PriorityQueue<br>Queue&lt;String&gt; cars = new PriorityQueue&lt;&gt;();<br>// Natural order PriorityQueue with initialCapacity 10<br>Queue&lt;String&gt; cars = new PriorityQueue&lt;&gt;(10);<br>// Comparator-specified order PriorityQueue<br>Queue&lt;String&gt; cars = new PriorityQueue&lt;&gt;(Comparator.reverseOrder());</pre><p>To sum up, you must choose an implementation to create a queue, according to the needs of your application.</p><h3>4. Java Queue Methods</h3><p>In this section, we’ll take a deeper look at the methods we briefly discussed in the previous sections</p><h3>4.1 Java Queue Offer &amp; Add</h3><p>offer() and add() are quite similar, since they both have the same use case, to add an element to the queue.</p><p>However, add() will <strong>throw an exception if the queue is full</strong>; an example of an implementation that does specify a max capacity is ArrayBlockingQueue:</p><pre>Queue&lt;String&gt; queue = new ArrayBlockingQueue&lt;&gt;(1);<br><br>queue.offer(&quot;YLC&quot;);<br><br>// This will fail but not throw any exception<br>boolean wasInserted = queue.offer(&quot;YLC&quot;);<br>System.out.println(&quot;Was 2nd element inserted? &quot; + wasInserted);<br>// This will throw an exception<br>queue.add(&quot;YLC&quot;);</pre><p>The above will print:</p><pre>Was 2nd element inserted? false<br>Exception in thread &quot;main&quot; java.lang.IllegalStateException: Queue full<br>    at java.base/java.util.AbstractQueue.add(AbstractQueue.java:98)<br>    at java.base/java.util.concurrent.ArrayBlockingQueue.add(ArrayBlockingQueue.java:329)<br>    at Main.main(Main.java:24)</pre><p>Finally, both return a boolean that is true if the addition succeeded and false if not. As for possible exceptions:</p><p>add() may throw:</p><ul><li>IllegalStateException - If the queue is full</li><li>ClassCastException - Should the class of the element you tried to add cannot be added to this queue</li><li>NullPointerException - If the implementation forbids null elements</li><li>IllegalArgumentException - Should any property lead to failure of insertion</li></ul><p>While offer() may throw all of them but the first.</p><h3>4.2 Java Queue Poll &amp; Remove</h3><p>In the same fashion, both methods fulfill the same purpose, they remove elements from the queue.</p><p>Of course, the difference is that remove() will throw an exception if the queue is empty while poll() will not:</p><pre>Queue&lt;String&gt; queue = new LinkedList&lt;&gt;();<br><br>// s is null<br>String s = queue.poll();<br><br>// throws NoSuchElementException<br>queue.remove();</pre><p>Finally, both of them will return the element that was removed if they succeed.</p><h3>4.3 Java Queue Peek &amp; Element</h3><p>Last but not least, these two methods will retrieve the head of the queue without removing it. Just like the previous two methods, element() will throw NoSuchElementException if the queue is empty while peek() will just return null :</p><pre>Queue&lt;String&gt; queue = new LinkedList&lt;&gt;();<br><br>// s is null<br>String s = queue.peek();<br><br>// throws NoSuchElementException<br>queue.element();</pre><h3>5. Java Queue Implementations</h3><p>In this section, we’ll take a brief look at the most commonly used implementations of Queue .</p><h3>5.1 LinkedList</h3><p>This is the linked list implementation of the Dequeue(Double-ended Queue) interface that extends Queue and uses nodes that have one pointer for the next item and one for the previous.</p><h3>5.2 PriorityQueue</h3><p>This implementation should be used when you do not want to poll items based on the insertion order but are given a custom priority based on some characteristics. Moreover, internally it uses an object array to hold the data and it represents a balanced binary heap. Furthermore, this implementation <strong>does not allow null elements</strong>.</p><p>Concerning time complexity:</p><ul><li>offer, add, remove() and poll have O(log(n) time complexity</li><li>While remove(Object) and contains(Object) have O(n) time complexity</li></ul><p>Last but not least, when you do use any of the methods used to remove or retrieve elements( remove(), poll() and element(), peek() respectively), the highest priority item will be retrieved.</p><p>For example, let’s say you have a queue of people waiting at a public service but you want to prioritize the elderly. You could use a PriorityQueue like this:</p><pre>Queue&lt;Citizen&gt; queue = new PriorityQueue&lt;&gt;(Comparator.comparing(Citizen::age).reversed());<br><br>queue.add(new Citizen(&quot;AD7484&quot;, 20));<br>queue.add(new Citizen(&quot;AD7474&quot;, 80));<br>queue.add(new Citizen(&quot;AD7584&quot;, 45));<br>queue.add(new Citizen(&quot;AD7284&quot;, 65));<br>queue.add(new Citizen(&quot;AD7285&quot;, 32));<br><br>System.out.println(queue.poll());<br>System.out.println(queue.poll());<br>System.out.println(queue.poll());<br>System.out.println(queue.poll());<br>System.out.println(queue.poll());<br><br>// Citizen record<br>public record Citizen(String id, int age){};</pre><p>Of course, the above will print:</p><pre>Citizen[id=AD7474, age=80]<br>Citizen[id=AD7284, age=65]<br>Citizen[id=AD7584, age=45]<br>Citizen[id=AD7285, age=32]<br>Citizen[id=AD7484, age=20]</pre><p>As a final note, to traverse a priority queue, <strong>Java 8 forEach, for loop, for each loop or iterators can not guarantee the correct order</strong>. However, you can do it like this:</p><pre>Citizen[] sorted = queue.toArray(i -&gt; new Citizen[0]);<br>Arrays.sort(sorted);<br><br>for (Citizen citizen : sorted) {<br>    System.out.println(citizen);<br>}<br><br>// the Record must implement Comparable<br>// according to descending age order logic<br>public record Citizen(String id, int age) implements Comparable&lt;Citizen&gt; {<br><br>    @Override<br>    public int compareTo(Citizen o) {<br>        return Integer.compare(o.age, this.age);<br>    }<br>}</pre><p>As a result, if we run the snippet above, it will print:</p><pre>Citizen[id=AD7474, age=80]<br>Citizen[id=AD7284, age=65]<br>Citizen[id=AD7584, age=45]<br>Citizen[id=AD7285, age=32]<br>Citizen[id=AD7484, age=20]</pre><p>This means that you can’t use the queue directly to print all the elements in the correct order but you have to do it by converting the queue to an array and then sorting it.</p><h3>5.3 ArrayDeque</h3><p>This is the array implementation of a <strong>double-ended queue</strong> and uses a resizable array of type Object internally.</p><p>Finally, this implementation might lead to better performance than that of LinkedList.</p><h3>5.4 Synchronized Implementations</h3><p>Before we begin, a BlockingQueue is an implementation of the Queue that has additional operations so it will be able to handle insertions and removals efficiently while multiple threads are trying to add and remove elements.</p><p>Moreover, there is a more specific type of blocking queue, the TransferQueue, that waits for consumers to receive elements and it may be useful in messaging applications when producers want a confirmation that a message was actually received by a consumer.</p><p>Finally, before we dive into the synchronized implementations of Queue, there are 3 types of queues based on the boundary:</p><ul><li>A queue with a mandatory boundary(you cannot create it without specifying a maximum capacity)</li><li>A queue with an optional boundary(you can specify a maximum capacity or have limitless capacity)</li><li>A queue without any boundaries</li></ul><p><strong>Now let’s explain briefly all the synchronized implementations:</strong></p><ul><li>ArrayBlockingQueue - A blocking and fixed-capacity queue(mandatory boundary) that is backed by an array.</li><li>ConcurrentLinkedDeque - A thread-safe double-ended queue without any bounds, backed by a doubly-linked list.</li><li>ConcurrentLinkedQueue - A thread-safe queue without any bounds, backed by a linked list with nodes that only point to the next element.</li><li>DelayQueue - An unbounded blocking queue in which an element can be taken only after the expiration of its delay.</li><li>LinkedBlockingQueue - Just like ConcurrentLinkedQueue but it can be optionally bounded.</li><li>LinkedBlockingDeque - Just like ConcurrentLinkedDeque but it can be optionally bounded.</li><li>LinkedTransferQueue - A transfer queue backed by a singly-linked list</li><li>PriorityBlockingQueue - A boundless blocking queue with the same logic as PriorityQueue .</li><li>SynchronousQueue - A zero-capacity blocking queue that blocks upon insertion until the consumer receives the element. Likewise, the consumer blocks until a message is available.</li></ul><h3>6. When to Use a Queue</h3><p>First of all, you should use a classic queue( LinkedList or ArrayDeque implementation) when you want <strong>FIFO</strong> logic in your application.</p><p>On the other hand, you should use the PriorityQueue implementation, if you&#39;d like to poll or just peek at elements from the queue based on some custom criteria and not just insertion order.</p><p>Last but not least, if you are in a multithreaded environment and you want FIFO or any custom ordering logic, you should use any of the implementations that we described before, based on the requirements of your application.</p><h3>7. Conclusion</h3><p>After reading this article, you should have a basic understanding of what is a Queue, how it is implemented in Java, and what options you have regarding the implementations of the Queue interface. Moreover, you will be able to choose an implementation that suits the needs of the application you are trying to build.</p><h3>8. Sources</h3><p>[1]: <a href="https://docs.oracle.com/javase/tutorial/collections/interfaces/queue.html">The Queue Interface (The Java™ Tutorials &gt; Collections &gt; Interfaces) — Oracle</a></p><p>[2]: <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Queue.html">Queue (Java SE 11 &amp; JDK 11 ) — Oracle</a></p><p>[3]: <a href="https://docs.oracle.com/javase/tutorial/collections/implementations/queue.html">Queue Implementations (The Java™ Tutorials &gt; Collections &gt; Implementations) — Oracle</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0efc975a986d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Stack]]></title>
            <link>https://medium.com/@geonikpal/java-stack-09e4e7fa756f?source=rss-a724af3d3d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/09e4e7fa756f</guid>
            <category><![CDATA[core-java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[stack-data-structure]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Georgios Nikolaos Palaiologopoulos]]></dc:creator>
            <pubDate>Sat, 18 Feb 2023 19:00:43 GMT</pubDate>
            <atom:updated>2024-06-22T18:00:11.586Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zU1p1JRB7OGFJV1o40X4kw.png" /></figure><p>In this article, we’ll go through <strong>Java Stack</strong> data structure, through detailed examples.</p><h3>1. What is a Java Stack?</h3><p>A Java Stack is a <strong>LIFO</strong>(Last-In-First-Out) data structure which means that the last inserted item will be the first item that we will be able to remove from the stack or just peek at it. Moreover, as you should have already guessed, it maintains the insertion order.</p><p>An example of a real-life stack could be a stack of books as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*Qrh25u2Jqg_7rEkmAdFjGg.png" /></figure><p>To achieve this specific state, we would need to do the following:</p><ol><li>Push the “Clean Code” into the stack</li><li>Push the “Effective Java” into the stack</li><li>Push the “Java: A Beginners’ Guide, Eighth Edition” into the stack</li><li>Push the “Thinking in Java” into the stack</li></ol><p>Unlike in real life where you can grab any book and not destroy the stack, in Java, you would be able to remove the books only in reverse insertion order:</p><ol><li>Remove the “Thinking in Java” from the stack</li><li>Remove the “Java: A Beginners’ Guide, Eighth Edition” from the stack</li><li>Remove the “Effective Java” from the stack</li><li>Remove the “Clean Code” from the stack</li></ol><p>Nevertheless, you can traverse the stack and see what items it contains.</p><p>Last but not least, the <strong>Java Stack class extends the </strong><strong>Vector class</strong>(therefore it is <strong>synchronized</strong> and is a type of List) and offers the following methods:</p><ul><li>push - to push an item to the stack</li><li>pop - to remove an item from the stack</li><li>peek - to retrieve an item from the stack without removing it</li><li>empty - to check if the stack is empty</li><li>search - to find an item in the stack</li></ul><p>Of course, we will see in the next sections how these methods work.</p><p>An important note here is that as per <a href="https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/util/Stack.html">Oracle docs</a>, <strong>the Deque interface provides implementations with more complete and consistent LIFO operations, therefore, they should be favored against the Stack class</strong>.</p><h3>2. Java Stack Example</h3><pre>// Create a stack<br>Stack&lt;String&gt; books = new Stack&lt;&gt;();<br><br>//Add books to stack<br>books.push(&quot;Clean Code&quot;);<br>books.push(&quot;Effective Java&quot;);<br>books.push(&quot;Java: A Beginners&#39; Guide, Eighth Edition&quot;);<br>books.push( &quot;Thinking in Java&quot;);<br><br>// Look the item on the top<br>String thinkingInJava = books.peek();<br><br>//Search the stack for &quot;Java: A Beginners&#39; Guide, Eighth Edition&quot;<br>int index = books.search(&quot;Java: A Beginners&#39; Guide, Eighth Edition&quot;); // 2<br><br>//Check the size using inherited size()<br>int size = books.size(); // 4<br><br>//Remove 2 items of the stack<br>books.pop();<br>books.pop();<br><br>//Try to remove using vector method, does nothing<br>books.remove(&quot;Java: A Beginners&#39; Guide, Eighth Edition&quot;);<br><br>//Remove the rest 2 items<br>books.pop();<br>books.pop();<br><br>//Check if is empty<br>boolean isEmpty = books.empty(); //true</pre><p>In the example above, we demonstrated <strong>how to create a stack</strong>(since Stack has only an empty constructor, there is no other way). Then we <strong>pushed</strong> the 4 books, <strong>peeked</strong> at the item on the top, <strong>searched</strong> for an item, and <strong>removed</strong> two items. In the end, we tried to remove using the inherited method and as expected, it did not remove the item as it was not allowed(it wasn&#39;t on top).</p><h3>3. Java Stack Methods</h3><p>In this section, we will take a deeper look at each method that is implemented inside the Stack class.</p><h3>3.1 Java Stack Push</h3><p>This method is used to add items to the stack</p><ul><li>It accepts the element to be inserted</li><li>Returns the element that was inserted</li><li>Has complexity O(1)</li></ul><pre>//Push a book<br>String cleanCode = books.push(&quot;Clean Code&quot;);</pre><h3>3.2 Java Stack Pop</h3><p>This method is used to remove items from the stack.</p><ul><li>It accepts no arguments</li><li>Returns the element that was removed</li><li>Throws an EmptyStackException if the stack is empty</li><li>Has complexity O(1)</li></ul><pre>//Remove a book<br>String cleanCode = books.pop();</pre><h3>3.3 Java Stack Peek</h3><p>This method works just like pop and has the same complexity but with one big difference: <strong>it does not remove the element</strong> <strong>from the stack</strong>.</p><pre>//Push a book<br>String cleanCode = books.push(&quot;Clean Code&quot;);<br>//Peek the book<br>String cleanCode = books.peek();<br>//Peek again<br>// it will return &quot;Clean Code&quot;<br>String cleanCode = books.peek();</pre><h3>3.4 Java Stack Search</h3><p>This method is used to search for an item in the stack.</p><ul><li>It accepts the element to be searched</li><li>Returns a <strong>1-based index of the element</strong> that was found where <strong>1 is the item on top</strong> and <strong>n is the item on the bottom</strong>. It returns -1 if the element was not found in the stack</li><li>Has complexity O(n) , as it would require going through all the items in a worst-case scenario.</li></ul><pre>//Add books to stack<br>books.push(&quot;Clean Code&quot;);<br>books.push(&quot;Effective Java&quot;);<br>books.push(&quot;Java: A Beginners&#39; Guide, Eighth Edition&quot;);<br>books.push( &quot;Thinking in Java&quot;);<br><br>// 1<br>int topBook = books.search(&quot;Thinking in Java&quot;);<br>// 2<br>int secondBook = books.search(&quot;Java: A Beginners&#39; Guide, Eighth Edition&quot;);<br>// 3<br>int thirdBook = books.search(&quot;Effective Java&quot;);<br>// 4<br>int bottomBook = books.search(&quot;Clean Code&quot;);<br>// -1<br>int missingBook = books.search(&quot;The C++ Programming Language&quot;);</pre><h3>3.5 Java Stack Empty</h3><p>This method just returns true if the stack has no elements:</p><pre>books.push(&quot;Clean Code&quot;);<br>books.push(&quot;Effective Java&quot;);<br>// Stack has elements inside<br>// false<br>boolean empty = books.empty();<br>// Remove all the items from the stack<br>books.pop();<br>books.pop();<br>// true<br>empty = books.empty();</pre><h3>4. How to Traverse a Java Stack</h3><p>You have five options if you’d like to traverse a stack in Java:</p><p><strong>1. Using For Each Loop</strong></p><pre>for(String book : books) {<br>    System.out.println(book);<br>}</pre><p><strong>2. Using an Iterator</strong></p><pre>var it = books.iterator();<br>while (it.hasNext()) {<br>    System.out.println(it.next());<br>}</pre><p><strong>3. Using a ListIterator</strong></p><pre>var listIt = books.listIterator();<br>while (listIt.hasNext()) {<br>    System.out.println(listIt.next());<br>}</pre><p><strong>4. Using a SplitIterator</strong></p><pre>books<br>        .spliterator()<br>        .forEachRemaining(System.out::println);</pre><p><strong>5. Using a Java 8 forEach</strong></p><pre>books.forEach(System.out::println); <br>//or<br>books.stream().forEach(System.out::println); </pre><h3>5. When to Use a Stack in Java</h3><p>The most common use-case of the stack is <strong>backtracking or undoing things</strong>. You can think of any editor that you might be using that allows a undo operation, most commonly the Ctrl + Z shortcut.</p><p>Now consider a scenario in which writing a whole word or typing space is a single action:</p><ul><li>You wrote the word “You”</li><li>Then you typed a space</li><li>Then you wrote the word “Learn”</li><li>Then you typed a space</li><li>Then you wrote the word “Code”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*EmrTKYxdY86QPnvEWK0DRA.png" /></figure><p>Now let’s say you would like to undo the &quot; Code&quot; that you wrote; you would just need to remove the last two items that you pushed to the stack:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*7BQuoz6zAKPoPRXBjxQfDg.png" /></figure><p>From the above, you can understand that the stack data structure is a perfect fit for undoing things.</p><p>In the same fashion, another scenario in which a stack would be useful is when you are trying to find a solution for a problem that has specific steps. With this in mind, a perfect example is<strong> finding a way out of a labyrinth</strong> as you could try the following approach:</p><ul><li>If this path is a dead end, backtrack(<strong>remove from the stack the path that you chose before</strong>) and try a different path than the path you chose before.</li><li>If this is not a dead end, you will have to choose again a random path and repeat the previous steps.</li></ul><h3>6. Conclusion</h3><p>After reading this article, you should know what is a stack, how it works and what are its unique characteristics. Moreover, you know when you should use a stack and what is the time complexity of each operation.</p><h3>7. Sources</h3><p><strong>[1]:</strong> <a href="https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/util/Stack.html">Stack(Java SE 18 &amp; JDK 18) — Oracle</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09e4e7fa756f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exception Handling in Java — How to Use Try, Catch, Finally, Throw and Throws Keywords]]></title>
            <link>https://medium.com/@geonikpal/exception-handling-in-java-how-to-use-try-catch-finally-throw-and-throws-keywords-9a1625ea1a06?source=rss-a724af3d3d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a1625ea1a06</guid>
            <category><![CDATA[core-java]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[try-catch]]></category>
            <dc:creator><![CDATA[Georgios Nikolaos Palaiologopoulos]]></dc:creator>
            <pubDate>Sun, 12 Feb 2023 12:00:23 GMT</pubDate>
            <atom:updated>2024-06-17T20:51:20.631Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exception Handling in Java — How to Use Try, Catch, Finally, Throw and Throws Keywords</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kigTvcGp38KIG8pk2Q59fQ.png" /></figure><p>In this article, we will learn about <strong>exception handling in Java</strong>, through detailed examples.</p><h3>1. What is an Exception in Java</h3><p>An Exception, as the name suggests, is an <strong>error that is thrown when unexpected behavior occurs</strong>. We must always handle any possible exceptions since they could lead to catastrophic consequences for our application.</p><h3>2. Checked vs Unchecked Exceptions in Java</h3><p>There are two types of Exceptions in Java, <strong>Checked</strong> and <strong>Unchecked</strong>.</p><p>A checked exception is any exception that is recognizable at compile time; as a result, the compiler will mandate that you handle it in order for the app to be compiled successfully.</p><p>On the other hand, an unchecked exception is any exception that isn’t recognizable at compile time and might be thrown during runtime. Note that <strong>all unchecked exceptions that are not instances or children of Error class will extend the RuntimeException class</strong>.</p><p>Some examples of checked exceptions are:</p><ul><li>ClassNotFoundException - Thrown when an application tries to load a class but this class is missing</li><li>IOException- This is thrown when I/O operations fail</li><li>FileNotFoundException - This is a child class of IOException and it is thrown when we try to read or write to a file that couldn&#39;t be found</li></ul><p>As for unchecked exceptions:</p><ul><li><a href="https://youlearncode.com/nullpointerexception-in-java/">NullPointerException</a> - This is thrown when we try to access a field or call a method of a null object</li><li>IndexOutOfBoundsException - Thrown when we try to access a collection by providing an index that is out of range</li><li>ArrayIndexOutOfBoundsException - This is a more specific case of the previous exception and it is thrown when we try to access an array by providing an index that is out of range</li></ul><h3>3. Exception Classes UML</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*zaXM8tYTIVguB7atZ4bjcg.png" /></figure><p>Let’s explain the diagram a bit:</p><ul><li><strong>Throwable</strong>: This is the highest-level class and all Exceptions and Errors inherit from it.</li><li><strong>Exception</strong>: This class has as children all the classes that are related to exceptions that are expected to be handled via try-catch blocks</li><li><strong>Error</strong>: <strong>All Classes that extend the Error class are related to errors that SHOULD NOT be handled</strong>. Moreover, as you can infer, all these classes are categorized as unchecked exceptions</li><li>Finally, for the rest of the classes, we already explained in the previous section what is the difference between checked and unchecked exceptions.</li></ul><h3>4. How to Use a Try-Catch Block in Java</h3><p>In this section, we will see how you can use try-catch blocks to eliminate any possible exception that might be thrown.</p><h3>4.1 Simple Try-Catch Block</h3><pre>try {<br>  // code that might throw an exception<br>} catch(Exception e) {<br>   // actions when the exception is actually thrown<br>}</pre><p>Of course, you can replace the type of Exception with any child class of Exception. However, you need to be careful as if the type of exception is wrong, you will never catch the exception.</p><p>Consider the following example:</p><pre>String x = null;<br>try {<br>    String z = x.toLowerCase();<br>} catch (Exception e){<br>    e.printStackTrace();<br>}<br>System.out.println(&quot;It did not crash&quot;);</pre><p>It will print:</p><pre>java.lang.NullPointerException: Cannot invoke &quot;String.toLowerCase()&quot; because &quot;x&quot; is null<br>It did not crash</pre><p>As we did catch the exception and the e.printStackTrace() was called.</p><p>In the same fashion, the following would work:</p><pre>String x = null;<br>try {<br>    String z = x.toLowerCase();<br>} catch (NullPointerException e){<br>    e.printStackTrace();<br>}</pre><p>But if we had chosen the wrong type, i.e. ArithmeticException, the program would crash as the exception type would never match.</p><h3>4.2 Multiple Catch Blocks</h3><p>We can also have multiple catch blocks, by using the following syntax:</p><pre>try {<br>  // code that might throw an exception<br>} catch(AnotherTypeOfException1 e1) {<br>   // actions when the exception thrown is of type<br>   // AnotherTypeOfException1  <br>} catch(AnotherTypeOfException2 e2) {<br>   // actions when the exception thrown is of type<br>   // AnotherTypeOfException2<br>} catch(AnotherTypeOfException3 e3) {<br>   // actions when the exception thrown is of type<br>   // AnotherTypeOfException3<br>} ...</pre><p>From the above, you can understand that <strong>the order of the catch blocks matters and a parent exception must always come after a child exception</strong>.</p><p>For example:</p><pre>String x = null;<br>try {<br>    String z = x.toLowerCase();<br>} catch (Exception e){<br>    e.printStackTrace();<br>} catch (NullPointerException e){<br>    e.printStackTrace();<br>}</pre><p>Would produce the compile-time error:</p><pre>java: exception java.lang.NullPointerException has already been caught</pre><h3>4.3 Catching Multiple Types of Exceptions in a Single Catch Block</h3><p>Since Java 7, you are able to catch multiple types of exceptions in a single catch block, by using the | as shown below:</p><pre>try {<br>    //code to try<br>} catch (AnotherTypeOfException1 | AnotherTypeOfException2 | AnotherTypeOfException3 e){<br> // actions when either of the exceptions were caught <br>}</pre><p>By using this way to catch blocks, you could code different behavior depending on the type of exception you caught, now check the example below:</p><pre>// Generate a random int in [1,3]<br>int x = (int) (1 + Math.random() * 3);<br><br>try {<br>    switch (x) {<br>        case 1 -&gt; {<br>            int a = 5/0;<br>        } case 2 -&gt; {<br>            String s = null;<br>            var len = s.length();<br>        } case 3 -&gt; {<br>            String[] s = new String[0];<br>            var access = s[1];<br>        }<br><br>    }<br>} catch (ArithmeticException | NullPointerException | ArrayIndexOutOfBoundsException e) {<br>    if(e instanceof ArithmeticException) {<br>        System.out.println(&quot;Arithmetic Exception was Caught&quot;);<br>    } else if (e instanceof NullPointerException) {<br>        System.out.println(&quot;NullPointerException Exception was Caught&quot;);<br>    } else {<br>        System.out.println(&quot;ArrayIndexOutOfBoundsException Exception was Caught&quot;);<br>    }<br>}</pre><p>We just generate a random number between one and three and then based on the result we produce a type of exception. Afterward, we use the syntax we mentioned below to catch any type of these exceptions and perform different actions based on the type of the exception that was caught.</p><h3>4.4 Nested Try Catch Blocks</h3><p>Just like with If statements and loops, you can have nested try-catch blocks, for instance, check the example below where we have 2 nested try-catch blocks:</p><pre>try {<br>    String s = null;<br>    var x = s.length();<br>} catch (NullPointerException nullPointerException){<br>    nullPointerException.printStackTrace();<br>    try {<br>        double x = 5/0;<br>    } catch (ArithmeticException arithmeticException) {<br>        arithmeticException.printStackTrace();<br>        try {<br>           var array =  new String[2];<br>           String s1 = array[3];<br>        } catch (ArrayIndexOutOfBoundsException indexOutOfBoundsException) {<br>            indexOutOfBoundsException.printStackTrace();<br>        }<br>    }<br>}</pre><p>As you should have already guessed, the above will print all the exceptions:</p><pre>java.lang.NullPointerException: Cannot invoke &quot;String.length()&quot; because &quot;s&quot; is null<br>    at Main.main(Main.java:18)<br>java.lang.ArithmeticException: / by zero<br>    at Main.main(Main.java:22)<br>java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 2<br>    at Main.main(Main.java:27)</pre><h3>5. How to Use the Finally Keyword in Java</h3><p>The finally keyword is used after a try or catch block and its purpose is to make sure that it is always get executed, no matter what happened with the try-catch blocks that you might have used.</p><h3>5.1 Finally Keyword Syntax</h3><p>The syntax of finally block is the following:</p><pre>try {<br>    // code to try<br>} finally {<br>    // code that will always be executed<br>}<br><br>OR<br><br>try {<br>    // code to try<br>} catch (ExceptionType1 e) {<br>    // code if an exception is thrown<br>} finally {<br>    // code that will always be executed<br>}</pre><h3>5.2 Finally Keyword Rules</h3><p>Let’s see what are the rules when using the finally keyword:</p><p>The first thing to remember is that the finally must always be last in a try-finally or try-catch-finally block. In addition, the only way for a finally block not to get executed is by calling System.exit() method. Furthermore, just like with try-catch blocks, we can have nested try-finally and try-catch-finally blocks.</p><p>Last but not least, to see how finally works with the return keyword, check the following examples:</p><pre>static int finallyTest1(){<br>    try {<br>        return -1;<br>    } catch (Exception e) {<br>        return -2;<br>    } finally {<br>        System.out.println(&quot;Hello&quot;);<br>        return -3;<br>    }<br>}<br><br>static int finallyTest2(){<br>    try {<br>        return -1;<br>    } catch (Exception e) {<br>        return -2;<br>    } finally {<br>        System.out.println(&quot;Hello&quot;);<br>    }<br>}</pre><p>In finallyTest1, the result will be:</p><pre>&quot;Hello&quot;<br>-3</pre><p>This means that the return inside the try block will not work if a return exists inside the finally block</p><p>If we run the second method, we will see this:</p><pre>&quot;Hello&quot;<br>-1</pre><p>As you can infer, we had a jump to the finally block code which was executed, and then the value inside the try block was returned.</p><h3>5.3 Try-Catch-Finally Block Example</h3><p>In the following example, we will try to connect to <a href="https://youlearncode.com/">https://medium.com</a> and read the result.</p><p>More specifically, we added a catch block to handle any IOException that might occur and finally, we disconnect using the <strong>finally block so that we are sure that we disconnected and we are not wasting any resources on an open connection</strong>:</p><pre>URL url;<br>HttpURLConnection connection = null;<br><br>try {<br>    url = new URL(&quot;https://medium.com&quot;);<br>    connection = (HttpURLConnection) url.openConnection();<br>    connection.setRequestMethod(&quot;GET&quot;);<br><br>    BufferedReader br = new BufferedReader(<br>            new InputStreamReader(<br>                    connection.getInputStream()<br>            )<br>    );<br><br>    StringBuilder allContentBuilder = new StringBuilder();<br>    String line;<br><br>    while ((line = br.readLine()) != null) {<br>        allContentBuilder.append(line);<br>    }<br>    System.out.println(allContentBuilder);<br><br>} catch (IOException e) {<br>    e.printStackTrace();<br>} finally {<br>    Optional.ofNullable(connection).ifPresent(HttpURLConnection::disconnect);<br>}</pre><h3>6. How to Throw an Exception in Java</h3><p>It is pretty simple to throw an exception, you <strong>type the keyword </strong><strong>throw, followed by an instance of any class that is or extends the Throwable class</strong>. As we mentioned before, it is NOT suggested to catch Exceptions that are instances or children of Error class as these errors are mainly not meant to be caught.</p><p>For instance, we can throw a NullPointerException and then catch it like this:</p><pre>try {<br>    throw new NullPointerException(&quot;Throwing NPE for fun&quot;);<br>} catch (NullPointerException nullPointerException) {<br>    System.out.printf(&quot;Caught the NPE with detail message: %s&quot;, nullPointerException.getMessage());<br>}</pre><p>As you would expect, the above will print Caught the NPE with detail message: Throwing NPE for fun</p><h3>7. Java Throws Keyword</h3><p>When we are dealing with <strong>checked</strong> exceptions, it is <strong>mandatory to handle the exception</strong> in some way.</p><p>For instance, let’s say you have the main method that calls a method that can throw an IOException:</p><pre>public static void main(String[] args) {<br>    aMethodThatThrowsIOException();<br>}<br><br>static void aMethodThatThrowsIOException() {<br>    var lines = Files.readAllLines(Paths.get(&quot;file.txt&quot;));<br>}</pre><p>If you try to write the following on your own PC, the compiler will complain with that message java: unreported exception java.io.IOException; must be caught or declared to be thrown</p><p>So if you want your code to compile, you have three options:</p><p><strong>1. Handle the exceptions inside the method</strong>, <strong>using a try-catch block</strong></p><pre>public static void main(String[] args) {<br>    aMethodThatThrowsIOException();<br>}<br><br>static void aMethodThatThrowsIOException() {<br>    try {<br>        var lines = Files.readAllLines(Paths.get(&quot;file.txt&quot;));<br>    } catch (IOException e){<br>        e.printStackTrace();<br>    }<br>}</pre><p><strong>2. Let the caller handle it by using the </strong><strong>throws keyword and use a try-catch block in the caller</strong></p><pre>public static void main(String[] args) {<br>    try {<br>        aMethodThatThrowsIOException();<br>    } catch (IOException e){<br>        e.printStackTrace();<br>    }<br>}<br><br>static void aMethodThatThrowsIOException() throws IOException {<br>    var lines = Files.readAllLines(Paths.get(&quot;file.txt&quot;));<br>}</pre><p><strong>3. Do not handle the exceptions at all by using the </strong><strong>throws keyword in both the method and the caller</strong></p><pre>public static void main(String[] args) throws IOException {<br>        aMethodThatThrowsIOException();<br>}<br><br>static void aMethodThatThrowsIOException() throws IOException {<br>    var lines = Files.readAllLines(Paths.get(&quot;file.txt&quot;));<br>}</pre><p>Of course, you can understand that the third way is <strong>NOT</strong> suggested in any case.</p><h3>8. Java Try-With-Resources Block</h3><p>This feature was introduced in Java 7, and by taking advantage of it, you can <strong>eliminate the need to use the finally keyword given specific circumstances</strong>.</p><p>The syntax of a try-with-resources block is the following:</p><pre>try(AResource ar = new AResource){<br>    //use this resource<br>} catch(AnException e){<br>//actions when an exception is caugt<br>}</pre><p>Before we jump to an example, you should know some characteristics of try-with-resources block:</p><ul><li>The resource declared inside the parentheses must implement the AutoClosable interface, otherwise, the code will never compile</li><li>Different from try-catch-finally blocks, you can use try-with-resources without a catch block or finally block</li><li>A finally block can be added but it is redundant</li></ul><p>As an illustration, if we try to write the block shown below:</p><pre>try {<br>  throw new NullPointerException(&quot;NPE&quot;);<br>}</pre><p>We will get the java: &#39;try&#39; without &#39;catch&#39;, &#39;finally&#39; or resource declarations compile-time error. However, if you write the same as try-with-resources block(by adding a resource in the parentheses), it will compile successfully</p><p>Now without further ado, let’s see a real-world example of try-with-resources block:</p><pre>void printFile() throws IOException {<br><br>    try(BufferedReader br = new BufferedReader(new FileReader(&quot;file.txt&quot;))){<br>        String line;<br>        while ((line = br.readLine()) != null) {<br>            System.out.println(line);<br>        }<br>    }<br>}</pre><p>In the example above, we declare a BufferedReader inside the parentheses, and we are able to use it inside the try block to print the file. Here we should note that since IOException is a checked exception, hadn&#39;t we written throws IOException , we would be obliged to use a catch block for the code to compile.</p><h3>9. Creating your Own Exception in Java</h3><p>In some circumstances, you might need to create your own type of exception, depending on the needs of your application.</p><p>Let’s say that you need to throw an exception when a user tries to create an account with an existing username. You can just create a class that extends the RuntimeException class, override any method that you might need, or create your own additional methods.</p><p>This could be done as shown below:</p><pre>public class UsernameAlreadyExistsException extends RuntimeException {<br>    private String username;<br>    private String ip;<br><br>    public String getUsername() {<br>        return username;<br>    }<br><br>    public void setUsername(String username) {<br>        this.username = username;<br>    }<br><br>    public String getIp() {<br>        return ip;<br>    }<br><br>    public void setIp(String ip) {<br>        this.ip = ip;<br>    }<br><br>    public UsernameAlreadyExistsException(String message, String username, String ip){<br>        super(message);<br>        this.username = username;<br>        this.ip = ip;<br>    }<br><br>    @Override<br>    public void printStackTrace() {<br>        System.out.println(&quot;Do nothing when called&quot;);<br>    }<br>}</pre><p>Of course, if we want to demonstrate how this would work, we could do it like this:</p><pre>try {<br>    throw new UsernameAlreadyExistsException(&quot;User tried to sign up with a username that already exists&quot;, &quot;geonikpal&quot;, &quot;192.168.1.1&quot;);<br><br>} catch (UsernameAlreadyExistsException usernameAlreadyExistsException){<br>    System.out.println(usernameAlreadyExistsException.getMessage());<br>    System.out.println(usernameAlreadyExistsException.getUsername());<br>    System.out.println(usernameAlreadyExistsException.getIp());<br>    usernameAlreadyExistsException.printStackTrace();<br>}</pre><p>This would print the following:</p><pre>User tried to sign up with a username that already exists<br>geonikpal<br>192.168.1.1<br>Do nothing when called</pre><h3>10. Conclusion</h3><p>After reading this article, you should know everything about what are exceptions in Java, what is the hierarchy of the exception-related classes, and how to handle any exception. Finally, you will be able to use try, catch, finally, throw, and throws keywords while knowing what is their purpose and their differences.</p><h3>11. Sources</h3><p>[1]: <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html">The try-with-resources Statement — Exceptions</a></p><p>[2]: <a href="https://docs.oracle.com/javase/9/docs/api/java/lang/Exception.html">Exception (Java SE 9 &amp; JDK 9 ) — Oracle Help Center</a></p><p>[3]: <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html">How to Throw Exceptions (The Java™ Tutorials &gt; Essential Java Classes &gt; Exceptions)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a1625ea1a06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Method]]></title>
            <link>https://medium.com/@geonikpal/java-method-450c7f52ca44?source=rss-a724af3d3d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/450c7f52ca44</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java-method]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[core-java]]></category>
            <dc:creator><![CDATA[Georgios Nikolaos Palaiologopoulos]]></dc:creator>
            <pubDate>Fri, 20 Jan 2023 18:00:23 GMT</pubDate>
            <atom:updated>2024-06-19T17:12:09.719Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-smev4OjQzPu19xaXqxSuQ.png" /></figure><p>In this article, we’ll talk about Java Method. More specifically, you will learn how to declare, call, and apply the best practices regarding methods.</p><h3>1. What is a Java Method?</h3><p><strong>A Java method is just a block of code that ought to have a single responsibility and may or may not return a value</strong>. Furthermore, a method can be called by other methods or it can even call itself recursively. Finally, methods are used in order to eliminate duplication and enhance the readability of code.</p><h3>2. Java Method Syntax</h3><p>In this section, we’ll look at the minimum components that a method declaration needs to compile and then take a brief look at all the possible keywords that we can add.</p><h3>2.1 Basic Syntax</h3><p>When declaring a method, the only mandatory information that you must provide is the name of the method, return type, and any parameters that it might accept(it can accept zero, one or more parameters):</p><pre>return_type methodName(Type1 param1, Type2 param2, ..., TypeN paramN) {<br>  //Method implementation<br></pre><p>Let’s analyze the syntax a little:</p><ul><li>The return type can be void or any type of object that you might like.</li><li>When using the keyword void, you will never be able to return a value back to the caller, however, you can stop the method execution at any point by just typing return;</li><li>If you chose that the method should return a value, you must always return a value that matches the type of the return_type. To return a value, you just type return, followed by the variable name you want to return.</li><li>The name of each parameter must be unique</li></ul><p>As a result, a method declared as this would compile without any problem:</p><pre>void print(String s) {<br> System.out.println(s); <br>}</pre><p>Likewise, the following would work:</p><pre>String toUppercase(String s) {<br>  return s.toUpperCase();<br>}</pre><h3>2.2 Syntax with All Options</h3><p>In the previous section, we saw the minimum requirement when declaring a method. Nevertheless, we can add many more keywords in order to specify the specific characteristics of this method.</p><p>In the following snippet, you can see all the keywords that we can add when declaring a method but note that there are some rules on when you can use them together or not.</p><pre>[access_modifier -&gt; default(no keyword) or public or protected or private] [generic type] [final] [abstract] [default] [native] [static] [synchronized] return_type methodName(Type1 t1, Type2 t2, ..., TypeN tN) [throws Any_type_of_Exception1, Any_type_of_Exception2, ... Any_type_of_ExceptionN]</pre><p>While this syntax might be overwhelming, we will explain in a later section how and why we would use any of these keywords.</p><h3>3. Java Method Signature</h3><p>You can think of method signature as a way to identify uniquely a method that you have declared. More specifically, if someone asks you to provide a signature this method:</p><pre>public static void printFromFile(String fileName) throws IOException {<br>  //code to print from file<br>}</pre><p>You would just write: printFromFile(String)</p><p>With this in mind, since the method signature is unique, you will never be able to create another method with the same signature</p><h3>4. Java Method Example</h3><p>Let’s say that you need to create a public method(since we need to be able to call it in any class) that accepts a ticker of a stock(e.g. AAPL), the price that you bought this stock, the trading fee, and the tax percentage. You could have something like this:</p><pre>public class PnL {<br>    <br>    private final StockClient stockClient = new StockClient();<br>    <br>    public double calculatePnL(String ticker,<br>                               double priceBought,<br>                               double tradingFeeOfTransaction,<br>                               double taxPercent<br>) {<br>        double earningsOrLossBeforeTax = getCurrentPriceOfStock(ticker) - priceBought- tradingFeeOfTransaction;<br>        return earningsOrLossBeforeTax &gt; 0 ? <br>                earningsOrLossBeforeTax * (1 - taxPercent) : <br>                earningsOrLossBeforeTax;<br>    }<br><br>    private double getCurrentPriceOfStock(String ticker) {<br>        return stockClient.getCurrentPrice(ticker);<br>    }<br>}</pre><p>Here we created an additional private method, as we do not want it to be accessed by another class, that gets the live price of a ticker.</p><p>Now if we want to use this method, we could do it like this:</p><pre>PnL pnl = new PnL();<br>double earnings = pnl.calculatePnL(&quot;AAPL&quot;, 100d, 0.5d, 0.15d);</pre><p>And with the price of 134 as of the time of writing, we would get a net profit~= 28.5 USD.</p><p>Of course, note that this works with just one stock and if we needed more, we would need to add another parameter, e.g. units, to specify how many stocks we hold.</p><h3>5. How to Call a Method in Java</h3><p>To call a method, you just have to type the method name followed by parentheses that must have all the required arguments. For example, let’s say you have created this method in Math.java:</p><pre>public int abs(int x) {<br>  return x &lt;=0 ? -x : x;<br>}</pre><p>If you like to call this method for the number -5, you just write the following:</p><pre>Math math = new Math();<br>math.abs(-5);</pre><p>This means that you need to first create an object and then call the method, in case the method is not static.</p><p>On the other hand, if the method was declared as static, we could call them like this, without any need to create an object:</p><pre>Math.abs(-5);</pre><p>Last but not least, if the method is called from the same class, you do not need to use an object to call it:</p><pre>public class Main {<br>    <br>    public static void main(String[] args) {<br>        Main main = new Main();<br>        main.hello();<br>    }<br><br>    void hello(){<br>        hey();<br>    }<br>    <br>    void hey(){<br>        System.out.println(&quot;Hey&quot;);<br>    }<br>}</pre><p>As you can see, we called the hey() method inside the hello(), without using any object other than the initially created object inside main.</p><h3>6. Java Method Naming Convention</h3><p>In Java, the naming convention for methods is <strong>camel-case, with the first letter lowercase</strong>.</p><p>Let’s say we have a method that converts an object to JSON, we should name it like this:</p><pre>String objectToJson(Object object){} OR<br>String toJson(Object object){} </pre><p>but never like this:</p><pre>String ObjectToJson(Object object){} OR<br>String OBJECTTOJSON(Object object){} OR<br>String object_to_json(Object object){} </pre><h3>7. Java Method Types</h3><p>In this section, we will see all the method types that exist, based on adding extra keywords</p><h3>7.1 Access-Restricted Methods</h3><p>Based on adding public , private , protected or nothing, you specify the visibility of a method:</p><ul><li>public means any class can access it</li><li>protected means that only classes in the same package and subclasses can access it</li><li>private means it can be accessed that it can only be accessed from the same class</li><li>no keyword means that it is package-private</li></ul><p>To completely understand how access modifiers work, I suggest that you read <a href="https://medium.com/@geonikpal/access-modifiers-in-java-ab4865de8293">Access Modifiers in Java</a>.</p><h3>7.2 Generic Methods</h3><p>Generic methods allow you to have parameters of a type that can be chosen when the method is called. For example:</p><pre>public &lt;T&gt; void print(T t) {<br>  System.out.println(t);<br>}</pre><p>Can print any object that you can imagine.</p><h3>7.3 Abstract Methods</h3><p>Abstract methods are just methods without any implementation and you can only define them inside abstract classes or interfaces.</p><p>Additionally, since abstract methods have no implementation, they cannot be static nor final.</p><h3>7.4 Final Methods</h3><p>Final methods are just <strong>methods that can never be overridden in a subclass</strong>; read more about the final keyword in <a href="https://medium.com/@geonikpal/final-keyword-in-java-10dab7f9218a">Final Keyword in Java</a>.</p><h3>7.5 Default Methods</h3><p>Default methods were introduced in Java 8, and you can only use them inside Interfaces.</p><p>Their purpose is to have a default implementation inside an interface that can be overridden later by a class that implements this interface.</p><h3>7.6 Static Methods</h3><p>Static methods do not need any object instantiation and they can just be called by using the class name.</p><p>Additionally, static methods cannot be overridden, cannot be abstract, cannot access instance members and you cannot use the keyword this and super with them.</p><p>Last but not least, you should use them when you do not have any dependency on objects and when creating utility and helper methods.</p><h3>7.7 Synchronized Methods</h3><p>Synchronized methods are used in multithreaded environments and more specifically when a method should only be accessed by one thread at a time.</p><p>This means that if a thread accesses a synchronized method, it locks it until it finishes, making it impossible for another thread to interfere.</p><h3>8. Is Java Pass by Value or Pass by Reference?</h3><p>This is a classic Java interview question, for which <strong>the answer is by value</strong>.</p><p>Now consider the example below:</p><pre>public static void main(String[] args) {<br>    int a = 5, b = 6;<br>    add(a, b);<br>    System.out.println(a);<br>    System.out.println(b);<br>}<br><br>public static void add(int a, int b){<br>    a++;<br>    b++;<br>}</pre><p>You can see that we added 1 to both numbers passed as arguments, and after the method returns, we print the result. Here it is important to note that <strong>we do not actually pass any reference but just the copy of the values</strong>(5 and 6), and as a result, the values assigned to a and b <strong>will never change</strong> <strong>outside the scope of the add method</strong>, and the output will be the following:</p><pre>5<br>6</pre><p>On the other hand, if we had defined a class like the one shown below:</p><pre>public class Pair {<br>    private int a;<br>    private int b;<br><br>    public int getA() {<br>        return a;<br>    }<br><br>    public void setA(int a) {<br>        this.a = a;<br>    }<br><br>    public int getB() {<br>        return b;<br>    }<br><br>    public void setB(int b) {<br>        this.b = b;<br>    }<br>}</pre><p>And then we did the following:</p><pre>public static void main(String[] args) {<br>    Pair pair = new Pair(5, 6);<br>    add(pair);<br>    System.out.println(pair.a);<br>    System.out.println(pair.b);<br>}<br><br>public static void add(Pair pair){<br>    pair.setA(pair.getA() + 1);<br>    pair.setB(pair.getB() + 1);<br>}</pre><p>This time, the <strong>reference of the object</strong>(which is just a <strong>value that represents the memory location</strong>) will be passed and the values that its attributes have will actually change and the following will be printed:</p><pre>6<br>7</pre><p>With this in mind, you should always be careful how and what variables you pass as arguments so that you will always get the expected results</p><h3>9. Java Method Overloading</h3><p><strong>Method overloading</strong> is when we define multiple methods with the same name but with a different signature. Different signature means that either the type of the parameters and/or the number of the parameters is different between them.</p><p><strong>Note that changing the return type is not enough to differentiate the two methods</strong>.</p><p>Finally, you should know that this type of polymorphism always happens in compile time. Here is an example:</p><pre>public void printPersonInfo(String name){}<br><br>public void printPersonInfo(String name, String surname){}<br><br>public void printPersonInfo(String name, String surname, double salary){}</pre><p>All of the methods above are valid as although they have the same name, they have a different number of methods. Of course, they could just have different types and/or order of parameters and they would still be valid; so if we add this method, the code would compile as expected.</p><pre>public void printPersonInfo(String name, double salary, String surname){}</pre><h3>10. Java Method Overriding</h3><p><strong>Method overriding</strong> is when a subclass provides a specific implementation for a method already defined in its superclass. The method in the subclass must have the following:</p><ul><li>The same name as the method in the superclass.</li><li>The same parameter list (same signature).</li><li>The same return type, or a subtype of the return type declared in the superclass method (covariant return type).</li></ul><p>Unlike method overloading, it only happens on run-time.</p><p>Here is an example:</p><pre>public class Animal {<br><br>    void makeASound(){<br>        System.out.println(&quot;AAA&quot;);<br>    }<br>}<br><br>public class Cat extends Animal {<br><br>    @Override<br>    void makeASound() {<br>        System.out.println(&quot;Meow&quot;);<br>    }<br><br>}<br><br>public class Dog extends Animal {<br><br>    @Override<br>    void makeASound() {<br>        System.out.println(&quot;Woof&quot;);<br>    }<br><br>}</pre><p>Here you can notice that the implementation of makeASound method is overridden in the subclasses Cat and Dog since we know the specific sounds these animals produce.</p><p>Additionally, you should notice the @Override annotation whose purpose is to produce a compile time error in case the annotated method is not overridden.</p><h3>11. Java Method with Optional Parameters — Varargs</h3><p>Although in the previous sections, we stated that we need to always pass the arguments that the method signature requires, there is one exception, in which you can omit to add a specific parameter.</p><p>Varargs are effectively an array but you need to use the three-dot notation, along with the type of the parameter; for example, if you want a method that accepts 0, 1, or n Strings, you should declare it as shown below:</p><pre>public static void printVarargs(String... args) {<br>    for (String s : args) {<br>        System.out.println(s);<br>    }<br>}<br><br><br>public static void main(String[] args) {<br>    printVarargs();<br>    printVarargs(&quot;You&quot;);<br>    printVarargs(&quot;You&quot;, &quot;Learn&quot;);<br>    printVarargs(&quot;You&quot;, &quot;Learn&quot;, &quot;Code&quot;);<br><br>}</pre><p>As you can see, we called the method with 0, 1, 2, and 3 arguments, and the compiler will not complain.</p><p>All in all, you should consider that if you choose to use varargs, you have 2 limitations:</p><ul><li>You can use only one varargs parameter per method</li><li>The varargs parameter must always be the last in order</li></ul><h3>12. Java Method Reference</h3><p>Java Method Reference was introduced in Java 8, along with Lambdas, and is the most concise way to call a method.</p><p>First of all, the syntax is the following:</p><pre>Class_or_object::a_method</pre><p>and this will always return a Java 8 Function/Predicate/Consumer etc.</p><p>For example, the following method reference returns the sum of two numbers:</p><pre>BinaryOperator&lt;Integer&gt; integerSum = Integer::sum;</pre><p>In the above example, we refer to the sum method of the Integer class by using the :: operator.</p><p>If you needed to create a method reference that adds 4 integers and returns the result since there isn’t such a method in Integer class, you would have to create your own as shown below:</p><pre>public static void main(String[] args) {<br>    FourSum fourSum =  MethodReference::sum;<br>}<br><br>@FunctionalInterface<br>public interface FourSum {<br><br>    Integer sum(int a, int b, int c, int d);<br>}<br><br>public static int sum(int a, int b, int c, int d) {<br>    return a + b + c + d;<br>}</pre><p>Finally, to learn more about Java 8 Lambda Expressions and Method References, you should read <a href="https://medium.com/@geonikpal/java-lambda-expressions-4233a41eb3dd">Java Lambda Expressions</a>.</p><h3>13. Conclusion</h3><p>By now you should know what a method is in Java, what is the syntax of a method, what is a method signature and more importantly how to call a method. Moreover, you learned about the naming convention, how overloading and overriding work, and the various types of methods that exist.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=450c7f52ca44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Generics]]></title>
            <link>https://medium.com/@geonikpal/java-generics-8b85e366a9bf?source=rss-a724af3d3d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b85e366a9bf</guid>
            <category><![CDATA[generics-in-java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[core-java]]></category>
            <dc:creator><![CDATA[Georgios Nikolaos Palaiologopoulos]]></dc:creator>
            <pubDate>Sat, 07 Jan 2023 15:00:21 GMT</pubDate>
            <atom:updated>2024-06-23T11:24:57.063Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xHinZXtfQkmDNxSrRlaX6A.png" /></figure><p>In this article, we’ll talk about Java Generics and how you can use them, through examples.</p><h3>1. What are Java Generics?</h3><p>Java Generics were introduced in Java 5, and by utilizing them, you can <strong>make any class, interface, or method use members or variables that can be specified dynamically</strong>.</p><p>The syntax for a generic class or interface is the following:</p><pre>// A generic class that can have and use variables of type T1, T2 , T3<br>public class AClass&lt;T1, T2, T3&gt;<br><br>// A generic interface that can have and use variables of type T1, T2, T3<br>public interface AnInterface&lt;T1, T2, T3&gt;</pre><p>As for Methods:</p><pre>// A void method that accepts parameters of any three different or same types and returns nothing<br>&lt;T1,T2,T3&gt; void aVoidMethod(T1 t1, T2 t2, T3 t3)<br><br>// A returning method that accepts parameters of any three different or same types <br>//and returns a variable of a type the same as with the third parameter<br>&lt;T1,T2,T3&gt; T3 aReturningMethod(T1 t1, T2 t2, T3 t3)</pre><h3>1.1 Before Java 5</h3><p>Note that before Java 5, if you wanted to use a <a href="https://youlearncode.com/java-list/">List</a>, you would write this:</p><pre>List hello = new ArrayList();</pre><p>But this means that you would be able to add anything to this list since the list would hold Object elements:</p><pre>hello.add(&quot;h&quot;); // A String<br>hello.add(5); // An Integer<br>hello.add(true); // A boolean</pre><p>while if you needed to retrieve a value, you would need to cast the result from Object to the type this variable you expect to be:</p><pre>String s = (String) hello.get(0);<br>Integer i = (Integer) hello.get(1);<br>Boolean i = (Boolean) hello.get(2);</pre><h3>1.2 After Java 5 and Before Java 7</h3><p>After generics were introduced in Java 5, you can specify the type as shown below:</p><pre>List&lt;String&gt; hello = new ArrayList&lt;String&gt;();</pre><p>and as a result, if you try the same, you will get these compile errors:</p><pre>java: incompatible types: int cannot be converted to java.lang.String<br>java: incompatible types: boolean cannot be converted to java.lang.String</pre><p>Since now the List contains only Strings, you would not need to perform any casting.</p><h3>1.3 After Java 7</h3><p>Since Java 7, you do not need to add the type parameter in the right hand of the initialization since the compiler can determine which is the type. As a result, you could just write the following to initialize a list of strings:</p><pre>List&lt;String&gt; hello = new ArrayList&lt;&gt;();</pre><h3>1.4 Generics Naming Conventions</h3><p>As for the naming convention, according to oracle docs, you should use single and uppercase letters, so it will be easy to differentiate a type variable and an ordinary class or interface name.</p><blockquote><em>The most commonly used type parameter names are:</em></blockquote><blockquote>E — Element (used extensively by the Java Collections Framework)</blockquote><blockquote>K — Key</blockquote><blockquote>N — Number</blockquote><blockquote>T — Type</blockquote><blockquote>V — Value</blockquote><blockquote>S,U,V etc. — 2nd, 3rd, 4th types</blockquote><blockquote><em>Generic Types — Oracle Docs</em></blockquote><p>Finally, you should know that <strong>you can use generics only with references(String, Double, Object, Person, etc.) and NOT with primitives(int, double, boolean, etc.)</strong></p><h3>2. Why Use Generics?</h3><p><strong>Code Reusability:</strong> Java Generics promote code reusability since a single class, interface or method can be used differently depending on the type(s) that we will provide.</p><p><strong>No need for Casting</strong>: Before Java 5, when using a List, all the elements that were added inside a list were Objects</p><pre>List hello = new ArrayList();<br>hello.add(&quot;You&quot;); <br>hello.add(&quot;Learn&quot;); <br>hello.add(&quot;Code&quot;);</pre><p>Now notice that you cannot just retrieve an element at a specified index and as a result, the following</p><pre>String you = hello.get(0);</pre><p>would produce the java: incompatible types: java.lang.Object cannot be converted to java.lang.String compile error and the only way to make this work is to cast it explicitly:</p><pre>String you = (String) hello.get(0);</pre><p>Nevertheless, with Java Generics, we can just specify the type of the List on the creation and then retrieve any item without the need for casting:</p><pre>List hello = new ArrayList();<br>hello.add(&quot;You&quot;); <br>hello.add(5); <br>hello.add(2.5d);</pre><p><strong>Type Safety</strong>: From the previous benefit of using generics, you can understand that since a List holds elements of type Object, we can add anything inside as in Java anything extends Object. As a result, we could write the following before generics:</p><pre>List hello = new ArrayList();<br>hello.add(&quot;You&quot;); <br>hello.add(5); <br>hello.add(2.5d);</pre><p>This list now holds three elements, all of which have different types. With generics, we can forbid any addition of an element of another type. So if we like a list of Person objects, we would write</p><pre>List&lt;Person&gt; hello = new ArrayList();</pre><p>And we would never be able to add anything else other than Person objects.</p><h3>3. How to Use Java Generics in a Class</h3><p>As it has already been stated, to use generics in a class you just have to add a non-reserved keyword for any different type that you might need inside &lt;&gt; just after the class name; for instance, if you want your class to have 3 members all of which should be able to have different types, you can do it as shown below:</p><pre>public class GenericClass&lt;T1,T2,T3&gt; {<br><br>    private T1 var1;<br>    private T2 var2;<br>    private T3 var3;<br><br>    public GenericClass(T1 var1, T2 var2, T3 var3) {<br>        this.var1 = var1;<br>        this.var2 = var2;<br>        this.var3 = var3;<br>    }<br><br>}</pre><p>Then you will be able to construct any object with members of any type that you might want to use:</p><pre>GenericClass&lt;Integer, Double, Person&gt; gc1 = new GenericClass&lt;&gt;(<br>        5,<br>        2.5d,<br>        new Person(&quot;Geo&quot;, &quot;Pal&quot;)<br>);<br>GenericClass&lt;Boolean, String, Object&gt; gc2 = new GenericClass&lt;&gt;(<br>        true,<br>        &quot;Hello&quot;,<br>        null<br>);</pre><h3>4. How to Use Java Generic Methods</h3><p>In the class that we created before, you can use the types inside any method without any extra effort, for instance:</p><pre>void aVoidMethod(T1 aVar, T3 aVar2) {<br>    System.out.println(aVar);<br>    System.out.println(aVar2);<br>}<br><br>T3 aReturningMethod(T1 aVar, T3 aCVar) {<br>    if(aVar == null) {<br>        return aCVar;<br>    }<br>    return null;<br>}</pre><p>However, if these generic methods belonged to a non-generic class you would need to change them:</p><pre>&lt;T1,T2&gt; void aVoidMethod(T1 aVar, T3 aVar2) {<br>    System.out.println(aVar);<br>    System.out.println(aVar2);<br>}<br><br>&lt;T1,T3&gt; T3 aReturningMethod(T1 aVar, T3 aCVar) {<br>    if(aVar == null) {<br>        return aCVar;<br>    }<br>    return null;<br>}</pre><p>Since T1, T3 and T3 would be unknown if we didn’t and we would get:</p><pre>Cannot resolve symbol &#39;T1&#39;<br>Cannot resolve symbol &#39;T2&#39;<br>Cannot resolve symbol &#39;T3&#39;</pre><h3>5. WildCard Type</h3><p>The wildcard(?) is a symbol that can be used instead of a specific T we used before, and it represents an unknown type.</p><p>Note that you <strong>CAN NOT</strong> declare a class with a wildcard:</p><pre>//This is not allowed<br> public class WildCardClass&lt;?&gt; {}</pre><p>However, it is used in many cases, e.g. in the class ArrayList, you can find the following implementation where a Collection of an unknown type is used:</p><pre>public boolean removeAll(Collection&lt;?&gt; c) {<br>  return batchRemove(c, false, 0, size);<br>}</pre><p>In this case, if no restrictions from superclasses or interfaces existed, we could have written:</p><pre>public &lt;T&gt; boolean removeAll(Collection&lt;T&gt; c) {<br>  return batchRemove(c, false, 0, size);<br>}</pre><p>and the result would be the same.</p><p>Moreover, we can pass a wildcard type as an argument in a method or use it as a local variable:</p><pre>static void printEverythingInAList(List&lt;?&gt; list) {<br>    <br>    list.forEach(System.out::println);<br>    <br>    //Not allowed<br>    //list.add(new Object());<br>    <br>    List&lt;?&gt; anotherList =  List.of(&quot;aString&quot;);<br><br>    //Not allowed<br>    //anotherList.add(&quot;s&quot;);<br>}</pre><p>If we uncomment the 2 lines after //Not allowed, we will get Required type: capture of ? so we will never be able to add anything to a wildcard list. However, we can traverse and access a wildcard list without any error.</p><h3>6. Java Generics with Extends and Super Keyword</h3><p>You can also restrict the type of a type parameter or a wildcard, by adding the extends or super keyword.</p><p>Before we begin, consider that we have the following classes declared</p><pre>public class Person{}<br><br>public class Teacher extends Person {}<br><br>public class Student extends Person {}</pre><h3>6.1 Java Generics with Extends Keyword</h3><p>When using the extends keyword either with a type parameter or a wildcard, you specify that <strong>the type to be used will have a superclass the type you specified after the extends keyword</strong>.</p><p>Therefore, <strong>if we have a </strong><strong>List&lt;? extends Person&gt; means that the list can be of any type that</strong> <strong>extends the </strong><strong>Person class</strong>.</p><p>Now consider that we have the following:</p><pre>public class Person{}<br><br>public class Teacher extends Person {}<br><br>public class Student extends Person {}</pre><p>From the above, we can deduct the following when it comes to reading from these collections:</p><ul><li>We can read Person objects from all lists since you know that everything inside these lists contain objects that extend Person class</li><li>We <strong>cannot </strong>read Teacher objects since it wouldn’t be possible for us to know whether an object is of type Teacher, as it could be of type Student</li><li>We <strong>cannot </strong>read Student objects for the same reason</li></ul><p>As for writing:</p><ul><li>You cannot add any Person object, as the list could be of type Teacher</li><li>You cannot add any Teacher object, as the list could be of type Student</li><li>You cannot add any Student object for the same reason</li></ul><p>To summarize, should you use the extends keyword in a list, you will not be able to add anything to it and you would only be able to read objects of superclass type.</p><h3>6.2 Java Generics with super Keyword</h3><p>When using super keyword either with a type parameter or a wildcard, you specify that<strong> the type to be used will have a subclass of the type you specified after the </strong><strong>super keyword</strong>.</p><p>Therefore, <strong>if we have a </strong><strong>List&lt;? super Teacher&gt; means that the list can be of any type that has </strong><strong>Teacher as a subclass</strong>.</p><p>Now consider that we have the following:</p><pre>List&lt;? super Teacher&gt; personList1 = new ArrayList&lt;Teacher&gt;();  <br>// Teacher is-a Teacher<br>List&lt;? super Teacher&gt; personList2 = new ArrayList&lt;Person&gt;();<br>// Teacher is a subclass of Person<br>List&lt;? super Teacher&gt; personList3 = new ArrayList&lt;Object&gt;();  <br>// Teacher is a subclass of Object</pre><p>From the above, we can deduct the following when it comes to reading from these collections:</p><ul><li>We <strong>cannot </strong>read Teacher objects, since this list could be of type Person or Object</li><li>We <strong>cannot </strong>read Person objects since the list could be of type Object</li><li>We <strong>can only read objects</strong> since the only certain thing is that anything inside will be an object</li></ul><p>As for writing:</p><ul><li>You cannot add any Person object or Object object, as the list could be of type Teacher and Person respectively</li><li>You can only add Teacher objects since all of the declarations allow an element of type Teacher</li></ul><p>To summarize, should you use the super keyword in a list, you will be able to add only the elements on the right side of the ? super Something and you would only be able to read objects of type Object.</p><h3>7. Java Generics in the Function Interface</h3><p>In this section, we will take a look at the Function interface, which was introduced in Java 8, and explain how and why generics are used, so that you have a complete understating of generics in a real-world use case.</p><p>If we take a look at this interface, the first thing that we will notice is this:</p><pre>@FunctionalInterface<br>public interface Function&lt;T, R&gt; {</pre><p>The &lt;T, R&gt; are specified so we can have any type as a parameter and any return type.</p><p>As a result, we will be able to do any of the following:</p><pre>Function&lt;String,Integer&gt; stringToInteger = Integer::parseInt<br><br>Function&lt;Integer,String&gt; integerToString = String::valueOf;</pre><p>And whichever combination you can imagine.</p><p>Now take a look at these two functions:</p><pre>R apply(T t);<br><br>static &lt;T&gt; Function&lt;T, T&gt; identity() {<br>        return t -&gt; t;<br>}</pre><p>You can notice that in the first one, we didn’t use &lt;R&gt; again, since it is specified at the class level, while for the identity() it is needed since this method is static.</p><p>The last method that we will inspect is the following:</p><pre>default &lt;V&gt; Function&lt;T, V&gt; andThen(Function&lt;? super R, ? extends V&gt; after) {<br>    Objects.requireNonNull(after);<br>    return (T t) -&gt; after.apply(apply(t));<br>}</pre><p>For the andThen function, you can notice that we need to have the &lt;V&gt; in the signature as it isn&#39;t defined at the class level while the T and V are already defined at the class level and the method is not static.</p><p>Furthermore, the parameter is defined as Function &lt;? super R, ? extends V&gt; which means that:</p><ul><li>The input of the function must be of any type that has R as a subclass(as passing anything else wouldn’t work)</li><li>The return type must be of any type that has V as a superclass</li></ul><h3>8. Conclusion</h3><p>After reading this article, you should be able to use Java Generics to your own benefit and enhance the reusability of your code.</p><h3>9. Sources</h3><p>[1] : <a href="https://docs.oracle.com/javase/tutorial/java/generics/types.html">Generic Types (The Java™ Tutorials &gt;<br>Learning the Java Language &gt; Generics (Updated))</a> — Oracle Docs</p><p>[2]: <a href="https://stackoverflow.com/questions/4343202/difference-between-super-t-and-extends-t-in-java">Difference between &lt;? super T&gt; and &lt;? extends T&gt; in Java</a> — StackOverflow</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b85e366a9bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Data JPA]]></title>
            <link>https://medium.com/@geonikpal/spring-boot-data-jpa-788d6e6155ef?source=rss-a724af3d3d97------2</link>
            <guid isPermaLink="false">https://medium.com/p/788d6e6155ef</guid>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jpa]]></category>
            <dc:creator><![CDATA[Georgios Nikolaos Palaiologopoulos]]></dc:creator>
            <pubDate>Tue, 13 Dec 2022 21:00:22 GMT</pubDate>
            <atom:updated>2024-12-14T16:22:03.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9foktopuPgHzUrGRM2eX-g.png" /></figure><p>In this article, we’ll go through how you can use Spring Boot Data JPA and annotations like @OneToOne, @OneToMany, and @ManyToMany to define the relations between that tables</p><h3>1. Project Description</h3><p>Imagine that we would like to have something like an e-banking app and that we have 3 Entities:</p><ul><li>The BankUser, which is just the user of the App</li><li>The Account, a classic bank account that can have an owner, a name, and an IBAN</li><li>The Card, a classic debit 16-digit card with a CVV and an expiration date</li></ul><p>Moreover, the following rules apply to the relations between them, for this e-banking app:</p><ul><li>A single user can have N accounts and an account can have many owners(<strong>Many to Many Relationship</strong>)</li><li>A single user can have N cards, but a card should have only one owner(<strong>One to Many Relationship</strong>)</li><li>A card should only be connected to one account(<strong>One to One Relationship</strong>).</li><li>A card must always have an owner and always be connected to an account.</li></ul><h3>2. Setting Up the Project</h3><p>For this tutorial, we are using the <strong>IntelliJ IDEA Community edition</strong> which you can download <a href="https://www.jetbrains.com/idea/download/">here</a>.</p><p>If you are not using this IDE, you also need to download Maven <a href="https://maven.apache.org/download.cgi">here</a>.</p><p>The next step is to visit <a href="https://start.spring.io/">Spring initializr</a> and generate a project according to these settings shown in the image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*EfJ34EVC5vTyOgNosvp_aQ.png" /></figure><p>After having chosen the above options, press the GENERATE button, and a new spring boot project will be downloaded for you. Then you have to unzip the compressed archive and open the folder with your favorite IDE.</p><h3>3. Creating the Entities</h3><p>In this section, we will just create all the entities without any annotations of jakarta.persistence package</p><h3>3.1 Account Entity</h3><pre>package com.youlearncode.springBootJPA.model;<br><br>import java.util.Objects;<br>import java.util.Set;<br><br>public class Account {<br><br>    private Long id;<br><br>    private String accountName;<br><br>    private AccountType accountType;<br><br>    private Set&lt;BankUser&gt; bankUsers;<br><br>    private Card card;<br><br>    private String IBAN;<br><br>    public Long getId() {<br>        return id;<br>    }<br><br>    public void setId(Long id) {<br>        this.id = id;<br>    }<br><br>    public String getAccountName() {<br>        return accountName;<br>    }<br><br>    public void setAccountName(String accountName) {<br>        this.accountName = accountName;<br>    }<br><br>    public AccountType getAccountType() {<br>        return accountType;<br>    }<br><br>    public void setAccountType(AccountType accountType) {<br>        this.accountType = accountType;<br>    }<br><br>    public Set&lt;BankUser&gt; getBankUsers() {<br>        return bankUsers;<br>    }<br><br>    public void setBankUsers(Set&lt;BankUser&gt; bankUsers) {<br>        this.bankUsers = bankUsers;<br>    }<br><br>    public Card getCard() {<br>        return card;<br>    }<br><br>    public void setCard(Card card) {<br>        this.card = card;<br>    }<br><br>    public String getIBAN() {<br>        return IBAN;<br>    }<br><br>    public void setIBAN(String IBAN) {<br>        this.IBAN = IBAN;<br>    }<br><br>    @Override<br>    public boolean equals(Object o) {<br><br>        if (this == o) return true;<br>        if (!(o instanceof Account)) return false;<br>        Account account = (Account) o;<br>        return Objects.equals(id, account.id) &amp;&amp; Objects.equals(accountName, account.accountName) &amp;&amp; accountType == account.accountType;<br>    }<br><br>    @Override<br>    public int hashCode() {<br>        return Objects.hash(id, accountName, accountType, IBAN);<br>    }<br>}</pre><p>AccountType is just an Enum with 2 constants, SAVINGS and CHECKING.</p><h3>3.2 BankUser Entity</h3><pre>package com.youlearncode.springBootJPA.model;<br><br>import java.util.HashSet;<br>import java.util.Objects;<br>import java.util.Set;<br><br><br>public class BankUser {<br><br>    private Long id;<br><br>    private String name;<br><br>    private String surname;<br><br>    private String taxId;<br><br>    private Set&lt;Account&gt; accounts = new HashSet&lt;&gt;();<br><br>    private Set&lt;Card&gt; cards = new HashSet&lt;&gt;();<br><br>    public Long getId() {<br>        return id;<br>    }<br><br>    public void setId(Long id) {<br>        this.id = id;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public String getSurname() {<br>        return surname;<br>    }<br><br>    public void setSurname(String surname) {<br>        this.surname = surname;<br>    }<br><br>    public String getTaxId() {<br>        return taxId;<br>    }<br><br>    public void setTaxId(String taxId) {<br>        this.taxId = taxId;<br>    }<br><br>    public Set&lt;Account&gt; getAccounts() {<br>        return accounts;<br>    }<br><br>    public void setAccounts(Set&lt;Account&gt; accounts) {<br>        this.accounts = accounts;<br>    }<br><br>    public Set&lt;Card&gt; getCards() {<br>        return cards;<br>    }<br><br>    public void setCards(Set&lt;Card&gt; cards) {<br>        this.cards = cards;<br>    }<br><br>    @Override<br>    public boolean equals(Object o) {<br>        if (this == o) return true;<br>        if (!(o instanceof BankUser)) return false;<br>        BankUser bankUser = (BankUser) o;<br>        return Objects.equals(id, bankUser.id) &amp;&amp; Objects.equals(name, bankUser.name) &amp;&amp; Objects.equals(surname, bankUser.surname) &amp;&amp; Objects.equals(taxId, bankUser.taxId);<br>    }<br><br>    @Override<br>    public int hashCode() {<br>        return Objects.hash(id, name, surname, taxId);<br>    }<br>}</pre><h3>3.3 Card Entity</h3><pre>package com.youlearncode.springBootJPA.model;<br><br>import java.util.Objects;<br><br>public class Card {<br><br>    private Long id;<br><br>    private String number;<br><br>    private String cvv;<br><br>    private String expirationDate;<br><br>    private Account account;<br><br>    private BankUser bankUser;<br><br>    public Long getId() {<br>        return id;<br>    }<br><br>    public void setId(Long id) {<br>        this.id = id;<br>    }<br><br>    public String getNumber() {<br>        return number;<br>    }<br><br>    public void setNumber(String number) {<br>        this.number = number;<br>    }<br><br>    public String getCvv() {<br>        return cvv;<br>    }<br><br>    public void setCvv(String cvv) {<br>        this.cvv = cvv;<br>    }<br><br>    public String getExpirationDate() {<br>        return expirationDate;<br>    }<br><br>    public void setExpirationDate(String expirationDate) {<br>        this.expirationDate = expirationDate;<br>    }<br><br>    public Account getAccount() {<br>        return account;<br>    }<br><br>    public void setAccount(Account account) {<br>        this.account = account;<br>    }<br><br>    public BankUser getBankUser() {<br>        return bankUser;<br>    }<br><br>    public void setBankUser(BankUser bankUser) {<br>        this.bankUser = bankUser;<br>    }<br><br>    @Override<br>    public boolean equals(Object o) {<br>        if (this == o) return true;<br>        if (!(o instanceof Card)) return false;<br>        Card card = (Card) o;<br>        return Objects.equals(id, card.id) &amp;&amp; Objects.equals(number, card.number) &amp;&amp; Objects.equals(cvv, card.cvv) &amp;&amp; Objects.equals(expirationDate, card.expirationDate);<br>    }<br><br>    @Override<br>    public int hashCode() {<br>        return Objects.hash(id, number, cvv, expirationDate);<br>    }<br>}</pre><h3>4. Defining The Tables and Their Relations with Spring Boot Data JPA</h3><p>In this section, we will add annotations to the entities we created so will be able to insert, update and query the H2 Database without writing any SQL.</p><h3>4.1 @Entity Annotation</h3><p>With @Entity annotation, we mark a class as a table in the database; this annotation has only one attribute, name, that you can fill in case you&#39;d like to override the name of the class(by default it will be uppercased).</p><p>So our classes will look like this:</p><pre>@Entity<br>public class Account {<br><br>@Entity<br>public class BankUser {<br><br>@Entity<br>public class Card {</pre><h3>4.2 @Id and @GeneratedValue Annotations</h3><p>The next step is to define the primary key of the table and the way that we will generate it.</p><p>To mark a field as a primary key, you must use the @Id annotation.</p><p>Moreover, by default the strategy is AUTO and the persistence provider will pick the appropriate database for the particular database. However, you can choose one of the following strategies:</p><ul><li>TABLE, the persistence provider should assign the primary keys for this entity, using an <strong>underlying database table</strong></li><li>SEQUENCE, the persistence provider should assign the primary keys for this entity, using a <strong>database sequence</strong></li><li>IDENTITY, the persistence provider should assign the primary keys for this entity, using a <strong>database identity column</strong></li><li>UUID, the persistence provider should assign the primary keys for this entity, by generating an RFC 4122 UUID</li></ul><p>If none of the strategies suit your needs, you can define your own key generator by using @SequenceGenerator or @TableGenerator</p><h3>4.3 @ManyToMany Annotation for the Account and BankUser Relationship</h3><p>The @ManyToMany annotation has the following attributes all of which are optional:</p><ul><li>targetEntity - The entity class that is the target of the association</li><li>cascade - Choose the cascade type of the operations</li><li>fetch - Choosing if the association will be eagerly or lazily loaded, defaults to LAZY</li><li>mappedBy - Here we specify the field that owns the relationship, therefore, the entity that has mappedBy will be the non-owning side</li></ul><p>In our example, the owning side will be the BankUser entity, for which we have to add the following:</p><pre>@ManyToMany<br>@JoinTable(name = &quot;bank_user_account&quot;, joinColumns = @JoinColumn(name = &quot;bank_user_id&quot;, foreignKey = @ForeignKey(name = &quot;fk_bank_user_id_account&quot;)),<br>        inverseJoinColumns = @JoinColumn(name = &quot;account_id&quot;, foreignKey = @ForeignKey(name = &quot;fk_account_id_bank_user&quot;)))<br>private Set&lt;Account&gt; accounts = new HashSet&lt;&gt;();</pre><p>The @ManyToMany is to specify that the relationship will be many-to-many.</p><p>Moreover, we have to specify some information about the table that will hold the connection between the two tables, by using the @JoinTable annotation.</p><p>In this case, we override the name of the table by specifying the name attribute, we specify the joinColumns(owning side) and the inverseJoinColumns(non-owning side)</p><p>With this in mind, we also specify the name of the column in the new table and the foreign key name by using the @JoinColumn and @ForeignKey annotations. Likewise, we do the same for the non-owning side.</p><p>To better understand the above, below you can find a diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*ClDiaEK8Lhf7LsBMUgNsjw.png" /></figure><p>Different from the owning side, for the inverse side(Account class), we just have to specify the mappedBy as shown below:</p><pre>@ManyToMany(mappedBy = &quot;accounts&quot;) private Set&lt;BankUser&gt; bankUsers;</pre><h3>4.4 @OneToMany and @ManyToOne Annotations for the BankUser and Card Entity</h3><p>Now that we have understood how @ManyToMany works, it&#39;s easier to grasp these two, as for the owning side we will provide the @OneToMany annotation and a join column as shown below:</p><pre>@OneToMany<br>@JoinColumn(name = &quot;bank_user_id&quot;, foreignKey = @ForeignKey(name = &quot;fk_bank_user_id_cards&quot;))<br>private Set&lt;Card&gt; cards = new HashSet&lt;&gt;();</pre><p>and the diagram for this relationship will be the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*gbJef2Y_lckrKoBIYpEOdg.png" /></figure><p>However, in this case, the inverse side(Card entity) just needs the @ManyToOne annotation as shown below:</p><pre>@ManyToOne(optional = false) private BankUser bankUser;</pre><p>Since a card must always have an owner, we will not allow any insertion without a specific owner, by setting optional = false.</p><h3>4.5 @OneToOne Annotation for the Account and Card Relationship</h3><p>Finally, for the one-to-one relationship between the account and card entity, we have to add the following to the owning side(Card):</p><pre>@OneToOne(optional = false)<br>@JoinColumn(name = &quot;account_id&quot;, foreignKey = @ForeignKey(name = &quot;fk_account_id&quot;))<br>private Account account;</pre><p>Note that unless we add the attribute unique=true in @JoinColumn, cardinality will never be checked and we can end up with multiple cards being connected to an account. Moreover, since a card needs to be connected to exactly one account, we use optional = false just like before.</p><p>As for the non-owning side( Account) we just add the @OneToOne(mappedBy = &quot;account&quot;):</p><pre>@OneToOne(mappedBy = &quot;account&quot;) private Card card;</pre><p>Of course, the diagram for this relationship will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*C0pd3VAt5eurajdl9d2hOQ.png" /></figure><h3>5. Creating the Repositories &amp; Configuring H2 Database</h3><p>Now to test that everything that we configured works as expected, we have to enable the H2 console and specify the datasource url by adding the following to application.yml:</p><pre>spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE<br>spring.h2.console.enabled=true</pre><p>The next step is to add a Repository for every entity by extending the CrudRepository interface:</p><pre>AccountRepository.java:<br><br>package com.youlearncode.springBootJPA.repository;<br><br>import com.youlearncode.springBootJPA.model.Account;<br>import org.springframework.data.repository.CrudRepository;<br><br>public interface AccountRepository extends CrudRepository&lt;Account, Long&gt; {}<br><br>BankUserRepository.java:<br><br>package com.youlearncode.springBootJPA.repository;<br><br>import com.youlearncode.springBootJPA.model.BankUser;<br>import org.springframework.data.repository.CrudRepository;<br><br>public interface BankUserRepository extends CrudRepository&lt;BankUser, Long&gt; {}<br><br>CardRepository.java:<br><br>package com.youlearncode.springBootJPA.repository;<br><br>import com.youlearncode.springBootJPA.model.Card;<br>import org.springframework.data.repository.CrudRepository;<br><br>public interface CardRepository extends CrudRepository&lt;Card, Long&gt; {}</pre><h3>6. Creating a DataFiller class</h3><p>As a final step, we will create a @Component annotated class that implements CommandLineRunner. This Functional Interface has just one method void run(String... args) that we will implement so as we add the following data:</p><ul><li>2 Bank Users</li><li>3 Accounts<br>- The first one belongs to the first and second user<br>- The second one belongs only to the first user<br>- The third one belongs only to the second user</li><li>3 cards<br>- The first belongs to the first user and is connected to the first account<br>- The second belongs to the second user and is connected to the second account<br>- The last one belongs to the second user and is connected to the third account</li></ul><p>As a result, the DataFiller class would look like this(We use the save method to insert or update the data):</p><pre>package com.youlearncode.springBootJPA;<br><br>import com.youlearncode.springBootJPA.model.Account;<br>import com.youlearncode.springBootJPA.model.AccountType;<br>import com.youlearncode.springBootJPA.model.BankUser;<br>import com.youlearncode.springBootJPA.model.Card;<br>import com.youlearncode.springBootJPA.repository.AccountRepository;<br>import com.youlearncode.springBootJPA.repository.CardRepository;<br>import com.youlearncode.springBootJPA.repository.BankUserRepository;<br>import org.springframework.boot.CommandLineRunner;<br>import org.springframework.stereotype.Component;<br>import java.util.Set;<br><br>@Component<br>public class DataFiller implements CommandLineRunner {<br><br><br>    private final BankUserRepository bankUserRepository;<br>    private final CardRepository cardRepository;<br>    private final AccountRepository accountRepository;<br><br>    public DataFiller(BankUserRepository bankUserRepository,<br>                      CardRepository cardRepository,<br>                      AccountRepository accountRepository<br>    ) {<br>        this.bankUserRepository = bankUserRepository;<br>        this.cardRepository = cardRepository;<br>        this.accountRepository = accountRepository;<br>    }<br><br>    @Override<br>    public void run(String... args) throws Exception {<br><br>        //Bank User 1<br>        BankUser bankUser1 = new BankUser();<br>        bankUser1.setName(&quot;Geo&quot;);<br>        bankUser1.setSurname(&quot;Pal&quot;);<br>        bankUser1.setTaxId(&quot;85030530&quot;);<br><br>        bankUserRepository.save(bankUser1);<br><br>        //Bank User 2<br>        BankUser bankUser2 = new BankUser();<br>        bankUser2.setName(&quot;Akis&quot;);<br>        bankUser2.setSurname(&quot;Pal&quot;);<br>        bankUser2.setTaxId(&quot;905803980&quot;);<br><br>        bankUserRepository.save(bankUser2);<br><br>        //Account 1<br>        Account account1 = new Account();<br>        account1.setAccountName(&quot;My Checking Account&quot;);<br>        account1.setAccountType(AccountType.CHECKING);<br>        account1.setIBAN(&quot;3452323259672453&quot;);<br>        accountRepository.save(account1);<br><br>        //Account 2<br>        Account account2 = new Account();<br>        account2.setAccountName(&quot;My Savings Account&quot;);<br>        account2.setAccountType(AccountType.SAVINGS);<br>        account2.setIBAN(&quot;5097436843736604&quot;);<br>        accountRepository.save(account2);<br><br>        //Account 3<br>        Account account3 = new Account();<br>        account3.setAccountName(&quot;Another Savings Account&quot;);<br>        account3.setAccountType(AccountType.SAVINGS);<br>        account3.setIBAN(&quot;3432847044115201&quot;);<br>        accountRepository.save(account3);<br><br>        //Users - accounts relationships<br><br>        bankUser1.setAccounts(Set.of(account1, account2));<br>        bankUser2.setAccounts(Set.of(account1, account3));<br><br>        bankUserRepository.save(bankUser1);<br>        bankUserRepository.save(bankUser2);<br><br>        //First card<br>        Card card1 = new Card();<br><br>        card1.setNumber(&quot;4825386157071828&quot;);<br>        card1.setCvv(&quot;991&quot;);<br>        card1.setExpirationDate(&quot;11/27&quot;);<br>        card1.setBankUser(bankUser1);<br>        card1.setAccount(account1);<br>        cardRepository.save(card1);<br><br>        //Second card<br>        Card card2 = new Card();<br><br>        card2.setNumber(&quot;4702899117785600&quot;);<br>        card2.setCvv(&quot;943&quot;);<br>        card2.setExpirationDate(&quot;11/28&quot;);<br>        card2.setBankUser(bankUser2);<br>        card2.setAccount(account2);<br>        cardRepository.save(card2);<br><br>        //Third card<br>        Card card3 = new Card();<br><br>        card3.setNumber(&quot;0959313190380584&quot;);<br>        card3.setCvv(&quot;745&quot;);<br>        card3.setExpirationDate(&quot;11/28&quot;);<br>        card3.setBankUser(bankUser2);<br>        card3.setAccount(account3);<br>        cardRepository.save(card3);<br><br>    }<br>}</pre><h3>7. Running the App &amp; Inspecting the H2 Database</h3><p>As a final step, start the app and visit <a href="http://localhost:8080/h2-console">http://localhost:8080/h2-console</a>, the username is sa and just leave the password empty.</p><p><strong>Account Table:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*xHDvsRTHE12gs-4K.png" /></figure><p><strong>Bank User Table:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/0*4ra8ddMT1bSJDZZH.png" /></figure><p>The table that holds the data for Many-to-many relationship between bank users and accounts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*I9NHaNeSsyfd5mM9.png" /></figure><p><strong>Card Table:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/0*rdryGn_8_n8UiLLp.png" /></figure><h3>8. Retrieving the Users via BankUserRepository</h3><p>We can try to retrieve all users by adding the following line in DataFiller.java:</p><pre>Iterable&lt;BankUser&gt; userList = bankUserRepository.findAll();</pre><p>However, you will notice that only the information from this table is retrieved since if you set a breakpoint after retrieving the users, you can see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gAYX6zr3cLaHv6kn.png" /></figure><p>The LazyInitializationException will be thrown if we try to access the accounts or cards field of the user.</p><p>This happens because the default fetch type is Lazy. To actually be able to access for example the cards field, we can change the fetch type in BankUser entity as shown below:</p><pre>@OneToMany(fetch = FetchType.EAGER)<br>@JoinColumn(name = &quot;bank_user_id&quot;, foreignKey = @ForeignKey(name = &quot;fk_bank_user_id_cards&quot;))<br>private Set&lt;Card&gt; cards = new HashSet&lt;&gt;();</pre><p>As a result, if we do re-run the app we can see that we will also get the info about the cards, <strong>however, this way of fetching the cards for each user will result in the N+1 problem</strong> since we would have to run N(one for each user in order to fetch their card) and 1(The query to fetch all the users) queries.</p><p>In order to resolve this issue, we can remove the EAGER fetch type, and use the @NamedEntityGraph annotation as shown below, in the BankUser class:</p><pre>@Entity<br>@NamedEntityGraph(name = &quot;BankUser.cards&quot;, attributeNodes = {<br>        @NamedAttributeNode(&quot;cards&quot;)<br>})<br>public class BankUser {</pre><p>Then we have to create a method inside the BankUserRepository as shown below:</p><pre>@Query(&quot;SELECT bu FROM BankUser bu&quot;)<br>@EntityGraph(value = &quot;BankUser.cards&quot;)<br>List&lt;BankUser&gt; findAllWithCards();</pre><p>And as a last step, we should call this method in the DataFiller class:</p><pre>var bankUsersWithCards = bankUserRepository.findAllWithCards();</pre><h3>9. Conclusion</h3><p>After reading this article, you will be able to use jakarta.persistence annotations such as @OneToMany, @JoinColumn, or@JoinTable in order to specify the relationships between the entities. You can find the source code on our <a href="https://github.com/geonikpal/youlearncode-tutorials/tree/spring-boot-jpa/spring-boot-jpa">GitHub page</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=788d6e6155ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>