<?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 Miguel Duque on Medium]]></title>
        <description><![CDATA[Stories by Miguel Duque on Medium]]></description>
        <link>https://medium.com/@miguel.duque7?source=rss-f4424b4964e4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*k4qkJoDDJzL7yJHqrVmo0w.jpeg</url>
            <title>Stories by Miguel Duque on Medium</title>
            <link>https://medium.com/@miguel.duque7?source=rss-f4424b4964e4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 23:06:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@miguel.duque7/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[How to Paginate and Sort a Spring Boot Rest API with MongoDB NoSQL database]]></title>
            <link>https://medium.com/@miguel.duque7/how-to-paginate-and-sort-a-spring-boot-rest-api-with-mongodb-nosql-database-935e8bac6e87?source=rss-f4424b4964e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/935e8bac6e87</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[nosql]]></category>
            <dc:creator><![CDATA[Miguel Duque]]></dc:creator>
            <pubDate>Sat, 29 Jul 2023 18:39:52 GMT</pubDate>
            <atom:updated>2023-07-29T18:39:52.602Z</atom:updated>
            <content:encoded><![CDATA[<p>Pagination is often a requirement when our application handles a large dataset and we want to retrieve and return smaller chunks to the user.<br><br>Server-side pagination provides stability and scalability, so it is the natural preferable option to handle large amounts of data.<br><br>In this tutorial, we will learn how to easily guarantee that the data returned by our Spring Rest endpoint is already paginated and sorted, as well as how to retrieve the data from our MongoDB NoSQL database already paginated, by using the <strong>spring-boot-starter-data-mongodb</strong>.<br>We will also demonstrate how to configure a Rest endpoint to offer our client applications the necessary freedom to query and display the data as they prefer.<br><br>Dependencies required:</p><pre>implementation(&quot;org.springframework.boot:spring-boot-starter-web&quot;)<br>implementation(&quot;org.springframework.boot:spring-boot-starter-data-mongodb&quot;)</pre><h3>Setup MongoDB database</h3><p>First, we start by creating our <strong>Hospital</strong> collection.</p><pre>@NoArgsConstructor<br>@Getter<br>@Setter<br>@Document(collection = &quot;hospital&quot;)<br>public class Hospital {<br><br>    @Id<br>    private String id;<br>    private String name;<br>    private String phoneNumber;<br>    private String city;<br>}</pre><p>To retrieve our data, we will configure our MongoDB repository:</p><pre>public interface HospitalRepository extends MongoRepository&lt;Hospital, String&gt; {<br>}</pre><p>And finally the <strong>HospitalDto</strong> that our Rest endpoint will return:</p><pre>@NoArgsConstructor<br>@Setter<br>@Getter<br>public class HospitalDto {<br>    private Long id;<br>    private String name;<br>    private String phoneNumber;<br>}</pre><h3>Setup Spring Pageable API for Pagination</h3><p>The Spring <strong>Pageable</strong> API can be configured with 3 parameters:</p><ol><li>page – zero-based page index</li><li>size – the size of the page to be returned</li><li>sort – Spring <strong>Sort</strong> API which can be configured with the sort direction, and the database field that will be used for sorting</li></ol><p>So, we should configure those 4 fields with default values on our rest endpoint, create that Pageable object, and then return our Page:</p><pre>import org.springframework.data.domain.Page;<br>import org.springframework.data.domain.PageRequest;<br>import org.springframework.data.domain.Pageable;<br>import org.springframework.data.domain.Sort;<br><br>...<br><br>@GetMapping<br>public Page&lt;HospitalDto&gt; findAllByPage(@RequestParam(defaultValue = &quot;0&quot;) int page,<br>                                       @RequestParam(defaultValue = &quot;2&quot;) int sizePerPage,<br>                                       @RequestParam(defaultValue = &quot;ID&quot;) SortField sortField,<br>                                       @RequestParam(defaultValue = &quot;DESC&quot;) Sort.Direction sortDirection) {<br>    Pageable pageable = PageRequest.of(page, sizePerPage, sortDirection, sortField.getDatabaseFieldName());<br>    return hospitalService.findAllByPage(pageable);<br>}</pre><p>You probably noticed the <strong>SortField</strong> object. This is a custom enum to limit the allowed values that we accept for sorting. The string that we need to pass to the <strong>Sort</strong> object is the name of the field in our Entity object. For example, we should pass the string <strong>phoneNumber</strong>, the name of the field in the Java object:</p><pre>@Getter<br>@AllArgsConstructor<br>public enum SortField {<br>    ID(&quot;id&quot;),<br>    NAME(&quot;name&quot;),<br>    PHONE_NUMBER(&quot;phoneNumber&quot;);<br><br>    private final String databaseFieldName;<br>}</pre><h3>MongoDB Repository with Pagination</h3><p>So, the finalize our tutorial we just need to complete our service layer, which will retrieve the page from the database and map our database object to a DTO:</p><pre>@Service<br>public class HospitalServiceImpl implements HospitalService {<br><br>    private final HospitalRepository hospitalRepository;<br>    private final HospitalMapper hospitalMapper;<br><br>    @Autowired<br>    public HospitalServiceImpl(HospitalRepository hospitalRepository, HospitalMapper hospitalMapper) {<br>        this.hospitalRepository = hospitalRepository;<br>        this.hospitalMapper = hospitalMapper;<br>    }<br><br>    @Override<br>    public Page&lt;HospitalDto&gt; findAllByPage(Pageable pageable) {<br>        return hospitalRepository.findAll(pageable)<br>                                 .map(hospitalMapper::toDto);<br>    }<br>}</pre><p>The MongoDB spring repository supports out of the box the find all method with the <strong>Pageable</strong> object, so we just need to do</p><pre>hospitalRepository.findAll(pageable)</pre><p>And finally, we can simply use a mapping class to map the <strong>Hospital</strong> object to <strong>HospitalDto</strong>:</p><pre>hospitalRepository.findAll(pageable)<br>                  .map(hospitalMapper::toDto);</pre><p>In this example, I am using the MapStruct library to setup the mapping class. This open-source is very easy to use and setup. For this tutorial we just need to create:</p><pre>import org.mapstruct.Mapper;<br>import org.mapstruct.ReportingPolicy;<br>import org.myduque.data.dto.HospitalDto;<br>import org.myduque.data.model.Hospital;<br><br>@Mapper(componentModel = &quot;spring&quot;, unmappedTargetPolicy = ReportingPolicy.ERROR)<br>public interface HospitalMapper {<br>    HospitalDto toDto(Hospital hospital);<br>}</pre><p>In case you never came across with MapStruct, you can easily add it to your dependencies:</p><pre>implementation(&quot;org.mapstruct:mapstruct:1.5.3.Final&quot;)<br>annotationProcessor(&quot;org.mapstruct:mapstruct-processor:1.5.3.Final&quot;)</pre><p>And you can read my article <a href="https://medium.com/uphill-engineering-design/deep-dive-into-mapstruct-spring-7ddd8dac3d6d">Mapstruct Tutorial Guide with Spring</a> to learn how to extract the most of this great library.</p><h3>MongoDB Spring Repository Named queries with Pagination</h3><p>Like the default <strong>findAll()</strong> method, named queries also support the Pageable API by default.<br><br>For example, if we wish to filter by hospitals with a name like a specific string and then page them, we just need to create the following method in the repository:</p><pre>@Repository<br>public interface HospitalRepository extends MongoRepository&lt;Hospital,String&gt; {<br>    Page&lt;Hospital&gt; findAllByNameLike(String name, Pageable pageable);<br>}</pre><h3>Conclusion</h3><p>We just saw how easy it is to implement the useful pagination functionality in our Rest API and MongoDB repository.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=935e8bac6e87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Spring Data JPA Specifications to filter SQL queries with Join Tables]]></title>
            <link>https://medium.com/@miguel.duque7/how-to-use-spring-data-jpa-specifications-to-filter-sql-queries-with-join-tables-1e821178c76b?source=rss-f4424b4964e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e821178c76b</guid>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[filters]]></category>
            <category><![CDATA[join]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Miguel Duque]]></dc:creator>
            <pubDate>Sat, 22 Jul 2023 09:38:27 GMT</pubDate>
            <atom:updated>2023-07-22T09:38:27.914Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with data, filtering it while querying the database is always the best approach. Loading it to memory and filtering it afterwards should be avoided as it wastes unnecessary resources, it is usually slower, and if you are handling large amounts of data, it probably is not feasible.</p><p>In this tutorial we will use Spring Boot to create a full rest application that filters data as needed from our JPA repository, using Spring Data JPA Specifications. We will try several filters:</p><ul><li>Compares the value of a column</li><li>Verify if the value of a column is in a list of values</li><li>Join tables and filter based on the value of the One to Many relationship</li><li>Join tables and filter based on the value of the Many to One relationship</li></ul><p>Additionally, we will make all our filters optional in our Rest Endpoint with some neat and clean code.</p><p>Dependencies required:</p><pre>implementation(&quot;org.springframework.boot:spring-boot-starter-web&quot;)<br>implementation(&quot;org.springframework.boot:spring-boot-starter-data-jpa&quot;)<br>implementation(&quot;org.springframework.boot:spring-boot-starter-jdbc&quot;)</pre><h3>Setup Jpa repository</h3><p>First, we start by creating our database entities, a <strong>Hospital</strong> with <strong>Doctors</strong>.</p><pre>@Entity<br>@NoArgsConstructor<br>@Getter<br>@Setter<br>@Table(name = &quot;hospital&quot;)<br>public class Hospital {<br>    <br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    @Column<br>    private String name;<br>    <br>    @Column(name = &quot;phone_number&quot;)<br>    private String phoneNumber;<br>    <br>    private String city;<br>    <br>    @OneToMany(mappedBy = &quot;hospital&quot;, fetch = FetchType.EAGER)<br>    private List&lt;Doctor&gt; doctors;<br>}</pre><pre>@Getter<br>@Setter<br>@Entity<br>@Table(name = &quot;doctor&quot;)<br>public class Doctor {<br>    <br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    <br>    @ManyToOne(optional = false)<br>    @JoinColumn(name = &quot;hospital_id&quot;)<br>    <br>    private Hospital hospital;<br>    <br>    private String name;<br>    <br>    private String speciality;<br>}</pre><p>To retrieve our data, we will configure our JPA repositories. Usually, they would be like this:</p><pre>@Repository<br>public interface HospitalRepository extends JpaRepository&lt;Hospital, Long&gt; {<br>}<br></pre><pre>@Repository<br>public interface DoctorRepository extends JpaRepository&lt;Doctor, Long&gt; {<br>}</pre><p>But to allow filtering of the data, we will also extend our repositories with the JpaSpecificationExecutor interface. This interface will allow the execution of Specifications based on the JPA criteria API:</p><pre>@Repository<br>public interface HospitalRepository extends JpaRepository&lt;Hospital,Long&gt;, JpaSpecificationExecutor&lt;Hospital&gt; {<br>}</pre><pre>@Repository<br>public interface DoctorRepository extends JpaRepository&lt;Doctor,Long&gt;, JpaSpecificationExecutor&lt;Doctor&gt; {<br>}</pre><h3>Spring Rest Endpoint with optional request parameters</h3><p>So, our goal is to create two endpoints:</p><ol><li>Get a list of hospitals. This endpoint will have 3 optional filters that can be used together or individually:</li></ol><ul><li>Filter hospitals with a name like a specific string</li><li>Filter hospitals that have doctors with a specific speciality</li><li>Filter hospitals in specific cities</li></ul><pre>@RestController<br>@RequestMapping(&quot;/hospitals&quot;)<br>public class HospitalController {<br><br>    private final HospitalService hospitalService;<br><br>    @Autowired<br>    public HospitalController(HospitalService hospitalService) {<br>        this.hospitalService = hospitalService;<br>    }<br>    <br>    @GetMapping<br>    public List&lt;HospitalDto&gt; findAll(@RequestParam(required = false) String nameLike,<br>                                     @RequestParam(required = false) String doctorSpeciality,<br>                                     @RequestParam(required = false) List&lt;String&gt; cities) {<br>        return hospitalService.findAll(nameLike, doctorSpeciality, cities);<br>    }<br>}</pre><p>2. Get a list of doctors. This endpoint will have 1 optional filter:</p><ul><li>Filter doctors that belong to hospitals in specific cities</li></ul><pre>@RestController<br>@RequestMapping(&quot;/doctors&quot;)<br>public class DoctorController {<br>    <br>    private final DoctorService doctorService;<br>    <br>    @Autowired<br>    public DoctorController(DoctorService doctorService) {<br>        this.doctorService = doctorService;<br>    }<br>    <br>    @GetMapping<br>    public List&lt;DoctorDto&gt; findAll(@RequestParam(required = false) List&lt;String&gt; hospitalsCities) {<br>        return doctorService.findAll(hospitalsCities);<br>    }<br>}</pre><ul><li>And here are the Dto classes that we will return from our endpoints:</li></ul><pre>@NoArgsConstructor<br>@Setter<br>@Getter<br>public class HospitalDto {<br>    private Long id;<br>    private String name;<br>    private String phoneNumber;<br>    private String city;<br>    private List&lt;DoctorDto&gt; doctors;<br>}</pre><pre>@NoArgsConstructor<br>@Setter<br>@Getter<br>public class DoctorDto {<br>    private String name;<br>    private String speciality;<br>}</pre><h3>JPA Specifications for SQL queries</h3><p>Now, the only thing left to do is to create our service layer that will create the required JPA Specifications based on the request parameters passed by the user, and pass them as an argument to the repository.</p><p>To do this, we will start by creating 2 util classes to create our JPA Specification filters. One to filter hospitals, and another to filter doctors.</p><h4>JPA Specifications for Hospitals</h4><p>As mentioned above, our hospitals endpoint contains 3 optional request parameters. Each parameter will be converted into a specific JPA specification filter:</p><pre>import java.util.List;<br><br>import javax.persistence.criteria.Join;<br>import org.myduque.data.model.Doctor;<br>import org.myduque.data.model.Hospital;<br>import org.springframework.data.jpa.domain.Specification;<br><br>public class HospitalSpecification {<br><br>    private HospitalSpecification() {}<br><br>    // First request parameter filter: Get hospitals with name like a specific string<br>    public static Specification&lt;Hospital&gt; nameLike(String nameLike) {<br>        return (root, query, builder) -&gt; builder.like(root.get(&quot;name&quot;), &quot;%&quot; + nameLike + &quot;%&quot;);<br>    }<br>    <br>    /*<br>        Second request parameter filter: Get hospitals that have doctors with a specific speciality.<br>        This will require us to first join the hospital and doctor tables (OneToMany), and then applying the filter.<br>        To do this One to Many join (one hospital has many doctors), we need to use the Join criteria to accomplish it<br>     */<br>    public static Specification&lt;Hospital&gt; hasDoctorInSpeciality(String speciality) {<br>        return (root, query, builder) -&gt; {<br>            Join&lt;Doctor,Hospital&gt; hospitalDoctors = root.join(&quot;doctors&quot;);<br>            return builder.equal(hospitalDoctors.get(&quot;speciality&quot;), speciality);<br>        };<br>    }<br>    <br>    // Third request parameter filter: Get hospitals in one of the specified cities<br>    public static Specification&lt;Hospital&gt; inCity(List&lt;String&gt; cities) {<br>        return (root, query, builder) -&gt; root.get(&quot;city&quot;)<br>                                             .in(cities);<br>    }<br>}</pre><h4>JPA Specifications for Doctors</h4><p>Our doctors&#39; endpoint only contains 1 optional request parameter, so one JPA Specification is required:</p><pre>import java.util.List;<br><br>import javax.persistence.criteria.Path;<br>import org.myduque.data.model.Doctor;<br>import org.springframework.data.jpa.domain.Specification;<br><br>public class DoctorSpecification {<br><br>    private DoctorSpecification() {}<br>    <br>    /*<br>        Get doctors that belong to hospitals in specific cities<br>        This will require us to first join the doctor and hospital tables (ManyToOne), and then applying the filter.<br>        To do this Many To One join (each doctor has one hospital, but one hospital has many doctors), we need to use the Path criteria to accomplish it<br>        This would be the same in a OneToOne relationship<br>     */<br>    public static Specification&lt;Doctor&gt; fromHospitalInCity(List&lt;String&gt; cities) {<br>        return (root, query, builder) -&gt; {<br>            Path&lt;Doctor&gt; hospital = root.get(&quot;hospital&quot;);<br>            return hospital.get(&quot;city&quot;)<br>                           .in(cities);<br>        };<br>    }<br>}</pre><h3>Use JPA specification in the JPA Data Repository</h3><p>Now, to finally use or Specifications with our JPA Repository, we just need to code the service layer.</p><p>Starting with the HospitalService:</p><pre>import static org.myduque.repository.specification.HospitalSpecification.hasDoctorInSpeciality;<br>import static org.myduque.repository.specification.HospitalSpecification.inCity;<br>import static org.myduque.repository.specification.HospitalSpecification.nameLike;<br><br>@Service<br>public class HospitalServiceImpl implements HospitalService {<br><br>    private final HospitalRepository hospitalRepository;<br>    private final HospitalMapper hospitalMapper;<br><br>    @Autowired<br>    public HospitalServiceImpl(HospitalRepository hospitalRepository, HospitalMapper hospitalMapper) {<br>        this.hospitalRepository = hospitalRepository;<br>        this.hospitalMapper = hospitalMapper;<br>    }<br>    <br>    @Override<br>    public List&lt;HospitalDto&gt; findAll(String nameLikeFilter, String doctorSpeciality, List&lt;String&gt; cities) {<br>        // Only create specifications for fields with values:<br>        Specification&lt;Hospital&gt; filters = Specification.where(StringUtils.isBlank(nameLikeFilter) ? null : nameLike(nameLikeFilter))<br>                                                       .and(StringUtils.isBlank(doctorSpeciality) ? null : hasDoctorInSpeciality(doctorSpeciality))<br>                                                       .and(CollectionUtils.isEmpty(cities) ? null : inCity(cities));<br>                                                       <br>        // User our created Specification to query our repository<br>        return hospitalRepository.findAll(filters)<br>                                 .stream()<br>                                 .map(hospitalMapper::toDto)<br>                                 .toList();<br>    }<br>}</pre><p>And similarly, our DoctorService:</p><pre>@Service<br>public class DoctorServiceImpl implements DoctorService {<br><br>    private final DoctorRepository doctorRepository;<br>    private final DoctorMapper doctorMapper;<br>    <br>    @Autowired<br>    public DoctorServiceImpl(DoctorRepository doctorRepository, DoctorMapper doctorMapper) {<br>        this.doctorRepository = doctorRepository;<br>        this.doctorMapper = doctorMapper;<br>    }<br>    <br>    @Override<br>    public List&lt;DoctorDto&gt; findAll(List&lt;String&gt; hospitalsCities) {<br>        // Create a specification with a where condition, if the request specified cities<br>        Specification&lt;Doctor&gt; filters = Specification.where(CollectionUtils.isEmpty(hospitalsCities) ? null : fromHospitalInCity(hospitalsCities));<br>        return doctorRepository.findAll(filters)<br>                               .stream()<br>                               .map(doctorMapper::toDto)<br>                               .toList();<br>    }<br>}</pre><h4>Mapstruct to map our Model to DTO</h4><p>You may have noticed that both in the <strong>DoctorService</strong> and <strong>HospitalService</strong> we used a mapping class to map our model to a Dto:</p><pre>.map(hospitalMapper::toDto)</pre><p>and</p><pre>.map(doctorMapper::toDto)</pre><p>In this example, I am using the MapStruct library to setup the mapping class. This open-source is very easy to use and setup. For this tutorial we just need to create:</p><pre>import org.mapstruct.Mapper;<br>import org.mapstruct.ReportingPolicy;<br>import org.myduque.data.dto.HospitalDto;<br>import org.myduque.data.model.Hospital;<br><br>@Mapper(componentModel = &quot;spring&quot;, unmappedTargetPolicy = ReportingPolicy.ERROR)<br>public interface HospitalMapper {<br>    HospitalDto toDto(Hospital hospital);<br>}</pre><p>and</p><pre>import org.mapstruct.Mapper;<br>import org.mapstruct.ReportingPolicy;<br>import org.myduque.data.dto.DoctorDto;<br>import org.myduque.data.model.Doctor;<br><br>@Mapper(componentModel = &quot;spring&quot;, unmappedTargetPolicy = ReportingPolicy.ERROR)<br>public interface DoctorMapper {<br>    DoctorDto toDto(Doctor doctor);<br>}</pre><p>In case you never came across with MapStruct, you can easily add it to your dependencies:</p><pre>implementation(&quot;org.mapstruct:mapstruct:1.5.3.Final&quot;)<br>annotationProcessor(&quot;org.mapstruct:mapstruct-processor:1.5.3.Final&quot;)</pre><p>And you can read my article <a href="https://medium.com/uphill-engineering-design/deep-dive-into-mapstruct-spring-7ddd8dac3d6d">Mapstruct Tutorial Guide with Spring</a> to learn how to extract the most out of this great library.</p><h3>Return a Page with JPA specification and Pageable</h3><p>In my previous article, we were able to implement an example of Rest endpoint with pagination. Using both Pageable and Specification is relatively easy, we just need to do the following when requesting the repository:</p><pre>hospitalRepository.findAll(filters, pageable)</pre><p>If you want to learn more about Pagination, you can read my article <a href="https://medium.com/@miguel.duque7/how-to-paginate-and-sort-a-spring-boot-rest-api-with-sql-database-52f1274a6dcb">How to Paginate and Sort a Spring Boot Rest API</a>.</p><h3>JPA specification with Sort</h3><p>In another article, we were able to implement an example of Rest endpoint with sort. Like in the pagination, using both Sort and Specification is also simple, we just need to do the following when requesting the repository:</p><pre>hospitalRepository.findAll(filters, sort)</pre><p>If you want to learn more about Sorting, you can read my article <a href="https://medium.com/@miguel.duque7/how-to-sort-a-spring-boot-rest-api-with-sql-database-ef8856e4f032">How to Sort a Spring Boot Rest API</a>.</p><h3>Conclusion on JPA Specification</h3><p>We just saw how easy it is to implement clean and useful filters on our Rest API and JPA repositories.</p><p>Spring Data JPA Specification allows us to develop a clean and reusable way of creating queries without much SQL knowledge!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e821178c76b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Sort a Spring Boot Rest API with SQL database]]></title>
            <link>https://medium.com/@miguel.duque7/how-to-sort-a-spring-boot-rest-api-with-sql-database-ef8856e4f032?source=rss-f4424b4964e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef8856e4f032</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[sorting]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Miguel Duque]]></dc:creator>
            <pubDate>Sat, 15 Jul 2023 08:24:21 GMT</pubDate>
            <atom:updated>2023-07-15T08:24:21.710Z</atom:updated>
            <content:encoded><![CDATA[<p>Sorting is often a requirement for any data-driven application.</p><p>To avoid consuming client resources and improve the performance of our application, most of the time this sort is implemented on the server level.</p><p>In this tutorial, we will learn how to easily guarantee that the data returned by our Spring Rest endpoint is sorted, as well as how to retrieve the data already sorted from our SQL database using Spring Data JPA.<br>We will also demonstrate how to configure a Rest endpoint to offer our client applications the freedom to query and display the data they prefer.</p><p>Dependencies required:</p><pre>implementation(&quot;org.springframework.boot:spring-boot-starter-web&quot;)<br>implementation(&quot;org.springframework.boot:spring-boot-starter-data-jpa&quot;)<br>implementation(&quot;org.springframework.boot:spring-boot-starter-jdbc&quot;)</pre><h3>Setup Jpa repository</h3><p>First, we start by creating our <strong>Hospital</strong> database entity.</p><pre>@Entity<br>@NoArgsConstructor<br>@Getter<br>@Setter<br>@Table(name = &quot;hospital&quot;)<br>public class Hospital {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    @Column<br>    private String name;<br><br>    @Column(name = &quot;phone_number&quot;)<br>    private String phoneNumber;<br>}</pre><p>To retrieve our data, we will configure our JPA repository:</p><pre>public interface HospitalRepository extends JpaRepository&lt;Hospital, Long&gt; {<br>}</pre><p>And finally, the <strong>HospitalDto</strong> that our Rest endpoint will return:</p><pre>@NoArgsConstructor<br>@Setter<br>@Getter<br>public class HospitalDto {<br>    private Long id;<br>    private String name;<br>    private String phoneNumber;<br>}</pre><h3>Setup Spring Sort API</h3><p>The Spring <strong>Sort</strong> API can be configured with 2 parameters:</p><ol><li>direction – the sort direction, ASC (ascending) or DESC (descending)</li><li>properties – the database fields that will be used for sorting</li></ol><p>So, we should configure those 2 fields with default values on our rest endpoint, create that Sort object, and then return our List:</p><pre>import org.springframework.data.domain.Sort;<br><br>...<br><br>@GetMapping<br>public List&lt;HospitalDto&gt; findAllSort(@RequestParam(defaultValue = &quot;ID&quot;) SortField sortField,<br>                                     @RequestParam(defaultValue = &quot;DESC&quot;) Sort.Direction sortDirection) {<br>    Sort sort = Sort.by(sortDirection, sortField.getDatabaseFieldName());<br>    return hospitalService.findAllSorted(sort);<br>}</pre><p>You probably noticed the <strong>SortField</strong> object. This is a custom enum to limit the allowed values that we accept for sorting. The string that we need to pass to the <strong>Sort</strong> object is the name of the field in our Entity object. For example, we should pass the string <strong>phoneNumber</strong>, the name of the field in the Java object, instead of <strong>phone_number</strong>, the name of the field in the database table:</p><pre>@Getter<br>@AllArgsConstructor<br>public enum SortField {<br>    ID(&quot;id&quot;),<br>    NAME(&quot;name&quot;),<br>    PHONE_NUMBER(&quot;phoneNumber&quot;);<br><br>    private final String databaseFieldName;<br>}</pre><h3>Sort by different fields and directions</h3><p>As mentioned above, the second argument when creating the <strong>Sort</strong> object is a list of arguments, so if we want to sort by different fields, we just need to list them by priority:</p><pre>Sort sort = Sort.by(Sort.Direction.ASC, NAME.name(), ID.name(), PHONE_NUMBER.name());</pre><p>What if we want to use different directions for different fields? For example:</p><ol><li>First sort by name ascending</li><li>Then to resolve objects with the same name, order by phone number descending</li><li>And finally for objects with the same name and phone number, order by id ascending again</li></ol><p>This would also be easy:</p><pre>Sort sort2 = Sort.by(Sort.Direction.ASC, NAME.name())<br>                 .and(Sort.by(Sort.Direction.DESC, PHONE_NUMBER.name()))<br>                 .and(Sort.by(Sort.Direction.ASC, ID.name()));</pre><h3>JPA Data Repository with Sort</h3><p>So, the finalize our tutorial we just need to complete our service layer, which will retrieve the list from the database and map our database object to a Dto:</p><pre>@Service<br>public class HospitalServiceImpl implements HospitalService {<br><br>    private final HospitalRepository hospitalRepository;<br>    private final HospitalMapper hospitalMapper;<br><br>    @Autowired<br>    public HospitalServiceImpl(HospitalRepository hospitalRepository, HospitalMapper hospitalMapper) {<br>        this.hospitalRepository = hospitalRepository;<br>        this.hospitalMapper = hospitalMapper;<br>    }<br><br>    @Override<br>    public List&lt;HospitalDto&gt; findAllSorted(Sort sort) {<br>        return hospitalRepository.findAll(sort)<br>                                 .stream()<br>                                 .map(hospitalMapper::toDto)<br>                                 .toList();<br>    }<br>}</pre><p>The JPA repository supports out of the box the find all method with the <strong>Sort</strong> object, so we just need to do</p><pre>hospitalRepository.findAll(sort)</pre><p>And finally, we can simply use a mapping class to map the <strong>Hospital</strong> object to <strong>HospitalDto</strong>:</p><pre>hospitalRepository.findAll(sort)<br>                  .stream()<br>                  .map(hospitalMapper::toDto)<br>                  .toList();</pre><p>In this example, I am using the MapStruct library to set up the mapping class. This open-source is very easy to use and set up. For this tutorial, we just need to create:</p><pre>import org.mapstruct.Mapper;<br>import org.mapstruct.ReportingPolicy;<br>import org.myduque.data.dto.HospitalDto;<br>import org.myduque.data.model.Hospital;<br><br>@Mapper(componentModel = &quot;spring&quot;, unmappedTargetPolicy = ReportingPolicy.ERROR)<br>public interface HospitalMapper {<br>    HospitalDto toDto(Hospital hospital);<br>}</pre><p>In case you never came across with MapStruct, you can easily add it to your dependencies:</p><pre>implementation(&quot;org.mapstruct:mapstruct:1.5.3.Final&quot;)<br>annotationProcessor(&quot;org.mapstruct:mapstruct-processor:1.5.3.Final&quot;)</pre><p>And you can read my article <a href="https://medium.com/uphill-engineering-design/deep-dive-into-mapstruct-spring-7ddd8dac3d6d">Mapstruct Tutorial Guide with Spring</a> to learn how to extract the most out of this great library.</p><h3>Conclusion</h3><p>We just saw how easy it is to implement the useful sort functionality in our Rest API and JPA repositories.<br><br>Despite that, the sort functionalities are usually followed by the need for pagination, especially when we are handling large datasets and users will likely just look at the first results.<br><br>To find out how to easily add pagination to this feature, just follow my article <a href="https://medium.com/@miguel.duque7/how-to-paginate-and-sort-a-spring-boot-rest-api-with-sql-database-52f1274a6dcb">How to Paginate and Sort a Spring Boot Rest API from SQL database</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef8856e4f032" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Paginate and Sort a Spring Boot Rest API with SQL database]]></title>
            <link>https://medium.com/@miguel.duque7/how-to-paginate-and-sort-a-spring-boot-rest-api-with-sql-database-52f1274a6dcb?source=rss-f4424b4964e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/52f1274a6dcb</guid>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Miguel Duque]]></dc:creator>
            <pubDate>Sat, 08 Jul 2023 19:32:55 GMT</pubDate>
            <atom:updated>2023-07-08T19:32:55.164Z</atom:updated>
            <content:encoded><![CDATA[<p>Pagination is often a requirement when our application handles a large dataset and we want to retrieve and return smaller chunks to the user.</p><p>Server-side pagination provides stability and scalability, so it is the preferable option to handle large amounts of data.</p><p>In this tutorial, we will learn how to easily guarantee that the data returned by our Spring Rest endpoint is already paginated and sorted, as well as how to retrieve the data from our SQL database already paginated, by using the Spring Data JPA.<br>We will also demonstrate how to configure a Rest endpoint to offer our client applications the freedom to query and display the data they prefer.</p><p>Dependencies required:</p><pre>implementation(&quot;org.springframework.boot:spring-boot-starter-web&quot;)<br>implementation(&quot;org.springframework.boot:spring-boot-starter-data-jpa&quot;)<br>implementation(&quot;org.springframework.boot:spring-boot-starter-jdbc&quot;)</pre><h3>Setup Jpa repository</h3><p>First, we start by creating our <strong>Hospital</strong> database entity.</p><pre>@Entity<br>@NoArgsConstructor<br>@Getter<br>@Setter<br>@Table(name = &quot;hospital&quot;)<br>public class Hospital {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    @Column<br>    private String name;<br><br>    @Column(name = &quot;phone_number&quot;)<br>    private String phoneNumber;<br>}</pre><p>To retrieve our data, we will configure our JPA repository:</p><pre>public interface HospitalRepository extends JpaRepository&lt;Hospital, Long&gt; {<br>}</pre><p>And finally, the <strong>HospitalDto</strong> that our Rest endpoint will return:</p><pre>@NoArgsConstructor<br>@Setter<br>@Getter<br>public class HospitalDto {<br>    private Long id;<br>    private String name;<br>    private String phoneNumber;<br>}</pre><h3>Setup Spring Pageable API for Pagination</h3><p>The Spring <strong>Pageable</strong> API can be configured with 3 parameters:</p><ol><li>page — zero-based page index</li><li>size — the size of the page to be returned</li><li>sort — Spring <strong>Sort</strong> API which can be configured with the sort direction, and the database field that will be used for sorting</li></ol><p>So, we should configure those 4 fields with default values on our rest endpoint, create that Pageable object, and then return our Page:</p><pre>import org.springframework.data.domain.Page;<br>import org.springframework.data.domain.PageRequest;<br>import org.springframework.data.domain.Pageable;<br>import org.springframework.data.domain.Sort;<br><br>...<br><br>@GetMapping<br>public Page&lt;HospitalDto&gt; findAllByPage(@RequestParam(defaultValue = &quot;0&quot;) int page,<br>                                       @RequestParam(defaultValue = &quot;2&quot;) int sizePerPage,<br>                                       @RequestParam(defaultValue = &quot;ID&quot;) SortField sortField,<br>                                       @RequestParam(defaultValue = &quot;DESC&quot;) Sort.Direction sortDirection) {<br>    Pageable pageable = PageRequest.of(page, sizePerPage, sortDirection, sortField.getDatabaseFieldName());<br>    return hospitalService.findAllByPage(pageable);<br>}</pre><p>You probably noticed the <strong>SortField</strong> object. This is a custom enum to limit the allowed values that we accept for sorting. The string that we need to pass to the <strong>Sort</strong> object is the name of the field in our Entity object. For example, we should pass the string <strong>phoneNumber</strong>, the name of the field in the Java object, instead of <strong>phone_number</strong>, the name of the field in the database table:</p><pre>@Getter<br>@AllArgsConstructor<br>public enum SortField {<br>    ID(&quot;id&quot;),<br>    NAME(&quot;name&quot;),<br>    PHONE_NUMBER(&quot;phoneNumber&quot;);<br><br>    private final String databaseFieldName;<br>}</pre><h3>JPA Data Repository with Pagination</h3><p>So, the finalize our tutorial we just need to complete our service layer, which will retrieve the page from the database and map our database object to a DTO:</p><pre>@Service<br>public class HospitalServiceImpl implements HospitalService {<br><br>    private final HospitalRepository hospitalRepository;<br>    private final HospitalMapper hospitalMapper;<br><br>    @Autowired<br>    public HospitalServiceImpl(HospitalRepository hospitalRepository, HospitalMapper hospitalMapper) {<br>        this.hospitalRepository = hospitalRepository;<br>        this.hospitalMapper = hospitalMapper;<br>    }<br><br>    @Override<br>    public Page&lt;HospitalDto&gt; findAllByPage(Pageable pageable) {<br>        return hospitalRepository.findAll(pageable)<br>                                 .map(hospitalMapper::toDto);<br>    }<br>}</pre><p>The JPA repository supports out of the box the find all method with the <strong>Pageable</strong> object, so we just need to do</p><pre>hospitalRepository.findAll(pageable)</pre><p>And finally, we can simply use a mapping class to map the <strong>Hospital</strong> object to <strong>HospitalDto</strong>:</p><pre>hospitalRepository.findAll(pageable)<br>                  .map(hospitalMapper::toDto);</pre><p>In this example, I am using the MapStruct library to set up the mapping class. This open-source is very easy to use and set up. For this tutorial, we just need to create:</p><pre>import org.mapstruct.Mapper;<br>import org.mapstruct.ReportingPolicy;<br>import org.myduque.data.dto.HospitalDto;<br>import org.myduque.data.model.Hospital;<br><br>@Mapper(componentModel = &quot;spring&quot;, unmappedTargetPolicy = ReportingPolicy.ERROR)<br>public interface HospitalMapper {<br>    HospitalDto toDto(Hospital hospital);<br>}</pre><p>In case you never came across with MapStruct, you can easily add it to your dependencies:</p><pre>implementation(&quot;org.mapstruct:mapstruct:1.5.3.Final&quot;)<br>annotationProcessor(&quot;org.mapstruct:mapstruct-processor:1.5.3.Final&quot;)</pre><p>And you can read my article <a href="https://medium.com/uphill-engineering-design/deep-dive-into-mapstruct-spring-7ddd8dac3d6d">Mapstruct Tutorial Guide with Spring</a> to learn how to extract the most out of this great library.</p><h3>Conclusion</h3><p>We just saw how easy it is to implement the useful pagination functionality in our Rest API and JPA repositories.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52f1274a6dcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to study and pass AWS Cloud Practitioner Certification Exam (CCP — CLF-C01)]]></title>
            <link>https://medium.com/@miguel.duque7/how-to-study-and-pass-aws-cloud-practitioner-certification-exam-ccp-clf-c01-f67e7b8b9b3c?source=rss-f4424b4964e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f67e7b8b9b3c</guid>
            <category><![CDATA[ccp]]></category>
            <category><![CDATA[study]]></category>
            <category><![CDATA[certification]]></category>
            <category><![CDATA[aws-certification]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Miguel Duque]]></dc:creator>
            <pubDate>Sun, 02 Jul 2023 07:23:32 GMT</pubDate>
            <atom:updated>2023-07-02T07:23:32.611Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to study and pass AWS Cloud Practitioner Certification Exam (CCP — CLF-C01)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*9cUKeqVhscX0Y-EDoG9Ecg.png" /></figure><p>Amazon Web Services (AWS) is an outstanding cloud service provider of Amazon. Like Microsoft Azure and Google Cloud Platform (GCP), AWS operates in many regions and availability zones, offering hundreds of services globally, including computing, storage, and database.</p><p>So, if you work in IT, or if you wish to work in IT, it is essential to have a basic understanding of these cloud service providers. As AWS is a clear market leader, my recommendation is to start by learning it over its competitors.</p><p>Below is the AWS suggestion for the learning/certification path, which naturally starts with the Foundational Certification — AWS Cloud Practitioner (CLF-C01):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*69m3s3RDcJQUdZIVC4kGHw.png" /></figure><p>By studying to complete this certification, you will have a clear understanding of how the AWS platform works, the basic building blocks behind it, and most of the critical AWS services (if not all).</p><p>I recently cleared the AWS Cloud Practitioner Certification Exam, and thought of sharing my view on it, as well as the path I took to complete this certification.</p><p>The most common question related to this certification is <em>Do I need hands-on experience in AWS, or a computer science background to complete it?</em> The answer here is <strong>No</strong>.<br>It will obviously help if you have experience, but as the exam only contains multiple-choice questions, you can easily ace it by studying and watching some videos on the platform.</p><p>So, when I decided to complete the certification, I gathered 3 types of resources:</p><ul><li>A comprehensive course focused on the exam topics</li><li>Exam examples to practice</li><li>AWS free documentation</li></ul><p>And for 2 weeks, after work, I would focus on studying for the exam.</p><h3>AWS Cloud Practitioner Certification (CCP) Course</h3><p>I used the following Udemy Course to learn all the topics of the exam, plus a practice exam at the end:</p><p><a href="https://www.udemy.com/course/aws-certified-cloud-practitioner-new/">https://www.udemy.com/course/aws-certified-cloud-practitioner-new/</a></p><p>During the course, he recommends that you create an AWS account and reproduce everything that he is doing.<br>In my case, I just followed and comprehended the videos without reproducing them in my AWS account. You can definitely do it, but it will probably slow down your progress.</p><h3>AWS Cloud Practitioner Certification (CCP) practice exams</h3><p>After completing the course mentioned above, I focused on practising for exams.<br>I only took the certification once I could consistently get more than 90% score on the practice exams. To do this, I used the following Udemy courses, with 6 practice exams each:</p><ul><li><a href="https://www.udemy.com/course/aws-certified-cloud-practitioner-practice-test/">https://www.udemy.com/course/aws-certified-cloud-practitioner-practice-test/</a></li><li><a href="https://www.udemy.com/course/aws-certified-cloud-practitioner-practice-exams-c/">https://www.udemy.com/course/aws-certified-cloud-practitioner-practice-exams-c/</a></li></ul><p>You can also find many practice exams on YouTube.</p><p>Both during the course and practice exams, I would frequently use the <a href="https://aws.amazon.com/">AWS documentation</a> to clarify any questions that I might have.</p><h3>AWS Cloud Practitioner Certification (CCP) exam</h3><p>You can read the details of the exams by <a href="https://d1.awsstatic.com/training-and-certification/docs-cloud-practitioner/AWS-Certified-Cloud-Practitioner_Exam-Guide.pdf">clicking here</a>, but here is an overview:</p><ul><li>No Pre-requisite</li><li>Costs 100 USD</li><li>65 Questions (Multiple Choice and Multiple Response)</li><li>1 Attempts — If you fail, you can repeat it as many times as you want, but you must wait 14 days until your next attempt and will have to pay 100 USD every time</li><li>Delivery Method — Testing center or online proctored exam</li><li>Time — 90 minutes to complete the exam</li><li>Pass Minimum Score — 70</li></ul><h3>Conclusion</h3><p>Nowadays I use AWS daily, and I can definitely say that completing the certification gave me an edge. I have a clear understanding of many core services, and I understand the best use case for each feature, leading to better optimizations, cost savings, and increased cloud security.<br>Besides that, having a certification under your belt can prove helpful in this competitive industry.</p><p>Best of luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f67e7b8b9b3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turn on/off AWS Fargate @ AWS Pipelines]]></title>
            <link>https://medium.com/uphill-engineering-design/turn-on-off-aws-fargate-aws-pipelines-2a8ab09c3ebb?source=rss-f4424b4964e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a8ab09c3ebb</guid>
            <category><![CDATA[codebuild]]></category>
            <category><![CDATA[fargate]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-ecs]]></category>
            <category><![CDATA[eventbridge]]></category>
            <dc:creator><![CDATA[Miguel Duque]]></dc:creator>
            <pubDate>Mon, 25 Jul 2022 21:15:41 GMT</pubDate>
            <atom:updated>2022-07-25T21:15:41.409Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Ad9N7Fe8cEHrFXwOfSuVeQ.png" /></figure><h3>What is AWS Fargate</h3><p>AWS Fargate is a serverless technology provided by AWS. It is a simpler alternative to its competitor Kubernetes, as it offers a great low-maintenance container orchestration solution.</p><p>As a serverless service, with AWS Fargate, there are no upfront costs and you pay only for the resources you use. You pay for the amount of vCPU, memory, and storage resources. Despite that, and contrary to AWS Lambda functions where you pay per invocation, in AWS Fargate you need your service to be constantly running to be able to respond to incoming requests.</p><p>This leads us to our topic, how can we turn on/off an AWS Fargate cluster that might not be needed in specific periods of the day, for example:</p><ul><li>A staging cluster that is not used during the night</li><li>A testing cluster that only needs to be available to run end-to-end tests</li></ul><p>Turning off these types of clusters can really make a difference in your monthly bill.</p><h3>Turning on/off your cluster</h3><p>Unfortunately, AWS Fargate does not offer this option as other services like AWS Elastic Beanstalk. To do this, you must use a CLI command to scale the number of instances of each service in the cluster to 0.</p><p>For example, given this cluster named <strong>Staging-Cluster </strong>in the<strong> eu-central-1</strong> region:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*oi7i6V6rEHvspGcdiJF1sA.png" /></figure><p>To turn off the cluster, you need to execute the 3 following commands (one per service):</p><pre>ecs update-service --cluster <strong>Staging-Cluster</strong> --service <strong>first-service</strong> --region eu-central-1 --desired-count <strong>0</strong></pre><pre>ecs update-service --cluster <strong>Staging-Cluster</strong> --service <strong>second-service</strong> --region eu-central-1 --desired-count <strong>0</strong></pre><pre>ecs update-service --cluster <strong>Staging-Cluster</strong> --service <strong>third-service</strong> --region eu-central-1 --desired-count <strong>0</strong></pre><p>To turn on the cluster, it is the same command but it the desired-count argument to 1 (or more), for example:</p><pre>ecs update-service --cluster Staging-Cluster --service first-service --region eu-central-1 <strong>--desired-count 1</strong></pre><pre>ecs update-service --cluster Staging-Cluster --service second-service --region eu-central-1 <strong>--desired-count 1</strong></pre><pre>ecs update-service --cluster Staging-Cluster --service third-service --region eu-central-1 <strong>--desired-count 2</strong></pre><h3>Automation</h3><p>There are multiple ways to automate the execution of CLI commands. In this case, we will use 2 additional AWS services:</p><ul><li>An AWS pipeline service: <strong>Codebuild</strong></li><li><strong>Amazon EventBridge </strong>to trigger the executions</li></ul><h4>Creating a Codebuild Project</h4><ol><li>Search the <strong>Codebuild</strong> service</li><li>Select the <strong>Create Build Project </strong>button</li><li>Give it a name</li><li>Select <strong>No source</strong> on <strong>Source</strong> configuration</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-KsO5LqTuZsEZS_deW8FQ.png" /><figcaption>Codebuild Source configuration</figcaption></figure><p>5. Select one of the AWS Managed images on the <strong>Environment</strong> configuration, for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EftaKgdi5qHNPcauLnuLuQ.png" /><figcaption>Codebuild Environment configuration</figcaption></figure><p>6. Add the desired commands to your <strong>Buildspec</strong> configuration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R799TCD48LduJvAdaU4jjw.png" /><figcaption>Codebuild Buildspec configuration</figcaption></figure><p><em>Example:</em></p><pre>version: 0.2<br>phases:<br>  build:<br>    commands:<br>      - ecs update-service --cluster Staging-Cluster --service first-service --region eu-central-1 --desired-count 0<br>      - ecs update-service --cluster Staging-Cluster --service second-service --region eu-central-1 --desired-count 0<br>      - ecs update-service --cluster Staging-Cluster --service third-service --region eu-central-1 --desired-count 0</pre><p>7. Scroll to the end with all the default values and select <strong>Create Build Project</strong></p><p>8. Open your newly created build project and go to the <strong>Build details</strong> tab, as you will need the <strong>Project ARN</strong> in the following steps</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wAUNnQd9_KiGpdx5OeYkAQ.png" /><figcaption>Codebuild project Build details</figcaption></figure><h4>Give the correct permission to your Role</h4><p>If we try to execute the newly created Build Project, we will have the following error:</p><blockquote>An error occurred (AccessDeniedException) when calling the UpdateService operation: User: arn:aws:sts::1111111:assumed-role/codebuild-My-Build-Project-service-role/AWSCodeBuild-a1111aaa-11aa-1111–…. is not authorized to perform: ecs:UpdateService on resource: arn:aws:ecs:eu-central-1:….:service/Staging-Cluster/first-service because no identity-based policy allows the ecs:UpdateService action</blockquote><p>To solve this lack of permissions, you must:</p><ol><li>Search the IAM service</li><li>Find your role, in this case is <strong>codebuild-My-Build-Project-service-role </strong>(name can be found on the error message)</li><li>Select <strong>Add Permission </strong>&gt; <strong>Create inline policy </strong>and select the <strong>UpdateService </strong>action of the <strong>Elastic Container Service</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LtHfVH1XClLhilKt61gSqg.png" /><figcaption>Create policy to Update ECS services</figcaption></figure><h4>Scheduling the execution with Eventbridge</h4><ol><li>Search the <strong>Amazon Eventbridge </strong>service</li><li>Select <strong>Rules</strong></li><li>Select the <strong>Create rule </strong>button</li><li>Select <strong>Schedule </strong>rule type</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJFKBGeafKK_QRcRSoUEIA.png" /><figcaption>Amazon Eventbridge Rule detail</figcaption></figure><p>5. Define the schedule of your rule. Here are 2 examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Akzf47J5n76mzEh9_JdShw.png" /><figcaption>Run at 7AM of every weekday</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QcZQr9tJ9f_prCVrCSjFzg.png" /><figcaption>Run everyday at 21h00</figcaption></figure><p>6. Set your <strong>Codebuild</strong> project previously created as the <strong>target</strong> of your rule. <em>Above in this document, on </em><strong><em>step 8</em></strong><em> of </em><strong><em>Creating a Codebuild Project, </em></strong><em>you can view how to retrieve the </em><strong><em>Project ARN</em></strong><em> of your build project</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6OzO1eyf4ZEG68i_q3Qaow.png" /><figcaption>Target of Eventbridge rule</figcaption></figure><p>7. Create the new rule with default values on the rest of the configurations</p><h3>Conclusion</h3><p>This article described how to turn on/off an AWS Fargate cluster using the CLI. It also described one of several examples of how to automate it.</p><p>Naturally, there are multiple interesting next steps to better take advantage of performing automation in a pipeline (Codebuild service), for example, setting the source of the Codebuild project to a code repository that performs end-to-end tests.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a8ab09c3ebb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/uphill-engineering-design/turn-on-off-aws-fargate-aws-pipelines-2a8ab09c3ebb">Turn on/off AWS Fargate @ AWS Pipelines</a> was originally published in <a href="https://medium.com/uphill-engineering-design">UpHill Health | Engineering &amp; Design</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep dive into Mapstruct @ Spring]]></title>
            <link>https://medium.com/uphill-engineering-design/deep-dive-into-mapstruct-spring-7ddd8dac3d6d?source=rss-f4424b4964e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ddd8dac3d6d</guid>
            <category><![CDATA[mapping-tool]]></category>
            <category><![CDATA[mapstruct]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Miguel Duque]]></dc:creator>
            <pubDate>Mon, 14 Dec 2020 00:44:25 GMT</pubDate>
            <atom:updated>2023-07-10T10:50:03.607Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pX4oOEKCwx4rlBkPG9locA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@vananaarbeau">Beau Swierstra</a> on Unsplash</figcaption></figure><p>Being a Java developer, you definitely know that mapping POJOs is a standard task when developing multilayered applications.<br>Writing these mappings manually, besides being a boring and unpleasant task for developers, is also error-prone.</p><p><a href="https://mapstruct.org/">MapStruct</a> is an open-source Java library that generates mapper class implementations during compilation in a safe and easy way.</p><p>During this article, we will follow an example of how to take advantage of this powerful library to greatly reduce the amount of boilerplate code that would regularly be written by hand.</p><h3>Index</h3><ul><li>Basic Mappings</li><li>Mapping Different Property Name</li><li>Making sure every property is mapped</li><li>Mapping Child Entity property</li><li>Mapping the full Child Entity — Using another mapper</li><li>Mapping with a custom method</li><li><a href="http://twitter.com/BeforeMapping">@BeforeMapping</a> <a href="http://twitter.com/AfterMapping">@AfterMapping</a></li><li>Mapping with an additional parameter</li><li>Dependency injection on mapping methods</li><li>Updates</li><li>Patch Updates</li></ul><h3>Basic Mappings</h3><p>Let’s start our application with a basic model, which contains the class <strong>Doctor. </strong>Our service will retrieve this class from the model layer and then return a <strong>DoctorDto</strong> class.</p><p>Model class:</p><pre>@Data<br>public class Doctor {<br>   private int id;<br>   private String name;<br>}</pre><p>Dto class:</p><pre>@Data<br>public class DoctorDto {<br>   private int id;<br>   private String name;<br>}</pre><p>To do this, we should create our Mapper interface:</p><pre>@Mapper(componentModel = &quot;spring&quot;)<br>public interface DoctorMapper {<br>   DoctorDto toDto(Doctor doctor);<br>}</pre><p>As both classes have the same property names (<em>id</em> and <em>name</em>), mapstruct will include the mapping of both fields in the generated class:</p><pre>@Component<br>public class DoctorMapperImpl implements DoctorMapper {<br><br>    @Override<br>    public DoctorDto toDto(Doctor doctor) {<br>        if ( doctor == null ) {<br>            return null;<br>        }<br><br>        DoctorDto doctorDto = new DoctorDto();<br><br>        doctorDto.setId( doctor.getId() );<br>        doctorDto.setName( doctor.getName() );<br><br>        return doctorDto;<br>    }<br>}</pre><p>By adding <em>componentModel = “spring”</em>, the generated mapper will be a Spring bean and can be retrieved with the <em>@Autowired</em> annotation like any other bean:</p><pre>@Service<br>public class DoctorService {<br><br>   private final DoctorMapper doctorMapper;<br>   private final DoctorRepository doctorRepository;<br><br>   @Autowired<br>   public DoctorService(DoctorMapper doctorMapper, <br>                        DoctorRepository doctorRepository) {<br>     this.doctorMapper = doctorMapper;<br>     this.doctorRepository = doctorRepository;<br>   }<br><br>   public DoctorDto getDoctor(Integer id) {<br>     Doctor doctor = doctorRepository.findById(id);<br>     return doctorMapper.toDto(doctor);<br>   }<br>}</pre><h3>Mapping Different Property Name</h3><p>If we include a property <em>phone </em>in the <strong>Doctor</strong> class:</p><pre>@Data<br>public class Doctor {<br>   private int id;<br>   private String name;<br>   private String phone;<br>}</pre><p>To be mapped to <em>contact</em> in <strong>DoctorDto</strong>:</p><pre>@Data<br>public class DoctorDto {<br>   private int id;<br>   private String name;<br>   private String contact;<br>}</pre><p>Our mapper won&#39;t be able to map it automatically. To do this, we will need to create a rule for this mapping:</p><pre>@Mapper(componentModel = &quot;spring&quot;)<br>public interface DoctorMapper {<br><br>   @Mapping(source = &quot;phone&quot;, target = &quot;contact&quot;)<br>   DoctorDto toDto(Doctor doctor);<br>}</pre><h3>Making sure every property is mapped</h3><p>If we want to guarantee that we don&#39;t forget to map any target property, we can configure the <em>unmappedTargetPolicy </em>option on our mapper:</p><pre>@Mapper(<br>      componentModel = &quot;spring&quot;, <br>      <strong>unmappedTargetPolicy = ReportingPolicy.<em>ERROR</em></strong>)<br>public interface DoctorMapper {<br><br>   @Mapping(source = &quot;phone&quot;, target = &quot;contact&quot;)<br>   DoctorDto toDto(Doctor doctor);<br>}</pre><p>With this configuration, if we remove</p><blockquote>@Mapping(source = &quot;phone&quot;, target = &quot;contact&quot;)</blockquote><p>our code will fail during compilation with the error:</p><blockquote>Unmapped target property: “contact”. DoctorDto toDto(Doctor doctor);</blockquote><p>If for some reason, we want to ignore a target property, we can add:</p><blockquote>@Mapping(target = &quot;contact&quot;, ignore = true)</blockquote><p>Similarly, we can also guarantee that all source<em> </em>properties are mapped by configuring the <em>unmappedSourcePolicy</em> option.</p><h3>Mapping Child Entity property</h3><p>Most of the time, the class that we need to map contains child objects. For example:</p><pre>@Data<br>public class Doctor {<br>   private int id;<br>   private String name;<br>   private String phone;<br>   private Speciality speciality;<br>}</pre><pre>@Data<br>public class Speciality {<br>   private int id;<br>   private String name;<br>}</pre><p>And in our Dto, instead of the full speciality, we just need its name:</p><pre>@Data<br>public class DoctorDto {<br>   private int id;<br>   private String name;<br>   private String contact;<br>   private String specialityName;<br>}</pre><p>This situation is also straightforward with <em>mapstruct</em>:</p><pre>@Mapping(source = &quot;phone&quot;, target = &quot;contact&quot;)<br>@Mapping(source = &quot;speciality.name&quot;, target = &quot;specialityName&quot;)<br>DoctorDto toDto(Doctor doctor);</pre><h3>Mapping the full Child Entity — Using another mapper</h3><p>As before, our <strong>Doctor</strong> class has a child object <strong>Address</strong>:</p><pre>@Data<br>public class Doctor {<br>   private int id;<br>   private String name;<br>   private String phone;<br>   private Speciality speciality;<br>   private Address address;<br>}</pre><p>But in this case, we want to map it to a new object in our <strong>DoctorDto</strong> class:</p><pre>@Data<br>public class DoctorDto {<br>   private int id;<br>   private String name;<br>   private String contact;<br>   private String specialityName;<br>   private AddressDto address;<br>}</pre><p>To perform the mapping between Address and AddressDto class, we should create a different mapper interface:</p><pre>@Mapper(componentModel = &quot;spring&quot;)<br>public interface AddressMapper {<br>   AddressDto toDto(Address address);<br>}</pre><p>Then, in our <strong>DoctorMapper</strong> we should make sure that this mapper is used when mapping the <strong>Doctor </strong>to <strong>DoctorDto</strong>. This can be done with the &quot;<em>uses&quot;</em> option on the mapper configuration:</p><pre>@Mapper(<br>      componentModel = &quot;spring&quot;,<br>      unmappedTargetPolicy = ReportingPolicy.<em>ERROR</em>,<br>      <strong>uses = {AddressMapper.class}</strong>)<br>public interface DoctorMapper {<br><br>   @Mapping(source = &quot;phone&quot;, target = &quot;contact&quot;)<br>   @Mapping(source = &quot;speciality.name&quot;, target = &quot;specialityName&quot;)<br>   DoctorDto toDto(Doctor doctor);<br>}</pre><p>We will see that our <strong>DoctorMapperImpl</strong> will Autowire and use our <strong>AddressMapper</strong>:</p><pre>@Component<br>public class DoctorMapperImpl implements DoctorMapper {<br><br>    <strong>@Autowired</strong><br>    <strong>private AddressMapper addressMapper;</strong><br><br>    @Override<br>    public DoctorDto toDto(Doctor doctor) {<br>        if ( doctor == null ) {<br>            return null;<br>        }<br><br>        DoctorDto doctorDto = new DoctorDto();<br><br>        doctorDto.setSpecialityName( doctorSpecialityName(doctor));<br>        doctorDto.setContact( doctor.getPhone() );<br>        doctorDto.setId( doctor.getId() );<br>        doctorDto.setName( doctor.getName() );<br>        <strong>doctorDto.setAddress( <br>                addressMapper.toDto( doctor.getAddress() ) );</strong><br><br>        return doctorDto;<br>    }<br><br>    ...<br>}</pre><h3>Mapping with a custom method</h3><p>Let&#39;s now add a list of patients to our <strong>Doctor </strong>class:</p><pre>@Data<br>public class Doctor {<br>   private int id;<br>   private String name;<br>   private String phone;<br>   private Speciality speciality;<br>   private Address address;<br><strong>   private List&lt;Patient&gt; patients;</strong><br>}</pre><p>However, on our <strong>DoctorDto </strong>we only want the number of patients:</p><pre>@Data<br>public class DoctorDto {<br>   private int id;<br>   private String name;<br>   private String contact;<br>   private String specialityName;<br>   private AddressDto address;<br>   <strong>private int numPatients;</strong><br>}</pre><p>This mapping requires 2 things:</p><ul><li>A custom method with the <em>@Named</em> annotation</li><li>The <em>qualifiedByName</em> config on the Mapping annotation</li></ul><pre>@Mapper(<br>      componentModel = &quot;spring&quot;,<br>      unmappedTargetPolicy = ReportingPolicy.<em>ERROR</em>,<br>      uses = {AddressMapper.class})<br>public interface DoctorMapper {<br><br>   @Mapping(source = &quot;phone&quot;, target = &quot;contact&quot;)<br>   @Mapping(source = &quot;speciality.name&quot;, target = &quot;specialityName&quot;)<br>   <strong>@Mapping(<br>         source = &quot;patients&quot;, <br>         target = &quot;numPatients&quot;, <br>         qualifiedByName = &quot;countPatients&quot;)</strong><br>   DoctorDto toDto(Doctor doctor);<br><br>   <strong>@Named(&quot;countPatients&quot;)<br>   </strong>default int getNumPatients(List&lt;Patient&gt; patients) {<br>      if(patients == null) {<br>         return 0;<br>      }<br>      return patients.size();<br>   }<br>}</pre><h3><em>@BeforeMapping </em>@AfterMapping</h3><p>The previous example (mapping from <strong>List&lt;Patient&gt; patients</strong> to <strong>int numPatients</strong>) can also be done with <em>@BeforeMapping</em> and <em>@AfterMapping</em></p><pre>@Mapper(<br>      componentModel = &quot;spring&quot;,<br>      unmappedTargetPolicy = ReportingPolicy.<em>ERROR</em>,<br>      uses = {AddressMapper.class})<br>public interface DoctorMapper {<br><br>   <strong>@BeforeMapping</strong><br>   default void setList(Doctor doctor) {<br>      if (doctor != null &amp;&amp; doctor.getPatients() == null) {<br>         doctor.setPatients(new ArrayList&lt;&gt;());<br>      }<br>   }<br><br>   @Mapping(source = &quot;phone&quot;, target = &quot;contact&quot;)<br>   @Mapping(source = &quot;speciality.name&quot;, target = &quot;specialityName&quot;)<br>   @Mapping(target = &quot;numPatients&quot;, ignore = true)<br>   DoctorDto toDto(Doctor doctor);<br><br>   <strong>@AfterMapping</strong><br>   default void setNumPatients(Doctor doctor,<br>                               @MappingTarget DoctorDto doctorDto) {<br>      doctorDto.setNumPatients(doctor.getPatients().size());<br>   }<br>}</pre><p>These methods will be called in the beginning and end of our generated mapping method:</p><pre>@Override<br>public DoctorDto toDto(Doctor doctor) {<br>    <strong>setList( doctor );</strong><br><br>    if ( doctor == null ) {<br>        return null;<br>    }<br><br>    DoctorDto doctorDto = new DoctorDto();<br><br>    doctorDto.setSpecialityName( doctorSpecialityName( doctor ) );<br>    doctorDto.setContact( doctor.getPhone() );<br>    doctorDto.setId( doctor.getId() );<br>    doctorDto.setName( doctor.getName() );<br>    doctorDto.setAddress( addressMapper.toDto(doctor.getAddress()));<br><br>    <strong>setNumPatients( doctor, doctorDto );</strong><br><br>    return doctorDto;<br>}</pre><h3>Mapping with an additional parameter</h3><p>Let&#39;s check how to handle a situation where your mapper needs to receive an additional parameter, besides your Entity.</p><p>In this case, your Doctor class can only get the City Id:</p><pre>@Data<br>public class Doctor {<br>   private int id;<br>   private String name;<br>   private String phone;<br>   private Speciality speciality;<br>   private Address address;<br>   private List&lt;Patient&gt; patients;<br>   <strong>private int cityId;</strong><br>}</pre><p>But needs to map it to the City Name:</p><pre>@Data<br>public class DoctorDto {<br>   private int id;<br>   private String name;<br>   private String contact;<br>   private String specialityName;<br>   private AddressDto address;<br>   private int numPatients;<br>   private String cityName;<br>}</pre><p>Your service will fetch the list of cities and pass them to the mapper</p><pre>@Service<br>public class DoctorService {<br><br>   private final DoctorMapper doctorMapper;<br>   private final DoctorRepository doctorRepository;<br><br>   @Autowired<br>   public DoctorService(DoctorMapper doctorMapper) {<br>      this.doctorMapper = doctorMapper;<br>      this.doctorRepository = doctorRepository;<br>   }<br><br>   public DoctorDto getDoctor(Integer id) {<br>      Doctor doctor = doctorRepository.findById(id);<br>      List&lt;City&gt; cities = getCities();<br>      return doctorMapper.toDto(doctor, cities);<br>   }<br>}</pre><p>In our mapper, we need to:</p><ul><li>mark the additional parameter (list of cities) with <em>@Context</em> annotation</li><li>create a custom method to handle our mapping</li><li>request the context parameter (list of cities) on our custom mapping method</li></ul><pre>@Mapping(source = &quot;phone&quot;, target = &quot;contact&quot;)<br>@Mapping(source = &quot;speciality.name&quot;, target = &quot;specialityName&quot;)<br>@Mapping(target = &quot;numPatients&quot;, ignore = true)<br><strong>@Mapping(source = &quot;cityId&quot;,<br>      target = &quot;cityName&quot;,<br>      qualifiedByName = &quot;cityName&quot;)</strong><br>DoctorDto toDto(Doctor doctor, <strong>@Context List&lt;City&gt; cities</strong>);<br><br><strong>@Named(&quot;cityName&quot;)<br></strong>default String getCityName(int cityId,<strong> @Context List&lt;City&gt; cities</strong>) {<strong><br>   </strong>return cities.stream()<br>         .filter(city -&gt; city.getId() == cityId)<br>         .findAny()<br>         .map(City::getName)<br>         .orElse(null);<strong><br></strong>}</pre><h3>Dependency injection on mapping methods</h3><p>You will probably find yourself in situations where your custom mapping methods require another bean (another mapper, a repository, a service, etc).</p><p>In these situations, you will need to Autowire that bean to your mapper, so let&#39;s see an example of how to do it.</p><p>In this example, our <strong>Patient</strong> class will be an abstract class:</p><pre>@Data<br>public abstract class Patient {<br>   private int id;<br>   private String name;<br>   private int age;<br>}</pre><p>Which contains two implementations:</p><pre>public class Man extends Patient {<br>}</pre><pre>public class Woman extends Patient {<br>}</pre><p>As we previously saw, this is the state of our <strong>Doctor</strong> entity:</p><pre>@Data<br>public class Doctor {<br>   private int id;<br>   private String name;<br>   private String phone;<br>   private Speciality speciality;<br>   private Address address;<br>   <strong>private List&lt;Patient&gt; patients;</strong><br>   private int cityId;<br>}</pre><p>However, our <strong>PatientDto </strong>requires a distinct list for each concrete class:</p><pre>@Data<br>public class DoctorDto {<br>   private int id;<br>   private String name;<br>   private String contact;<br>   private String specialityName;<br>   private AddressDto address;<br>   private int numPatients;<br>   private String cityName;<br>   <strong>private PatientsDto patients;</strong><br>}</pre><p>And</p><pre>@Data<br>public class <strong>PatientsDto</strong> {<br>   <strong>private List&lt;ManDto&gt; men</strong> = new ArrayList&lt;&gt;();<br>   <strong>private List&lt;WomanDto&gt; women</strong> = new ArrayList&lt;&gt;();<br><br>   public void addMan(ManDto manDto) {<br>      men.add(manDto);<br>   }<br><br>   public void addWoman(WomanDto womanDto) {<br>      women.add(womanDto);<br>   }<br>}</pre><p>So to map these concrete classes, we should start by creating two mappers:</p><pre>@Mapper(componentModel = &quot;spring&quot;)<br>public interface WomanMapper {<br>   WomanDto toDto(Woman woman);<br>}</pre><pre>@Mapper(componentModel = &quot;spring&quot;)<br>public interface ManMapper {<br>   ManDto toDto(Man man);<br>}</pre><p>But to map from <strong>List&lt;Patient&gt; patients </strong>to <strong>PatientsDto patients</strong> we also need a different mapper that uses the newly created mappers (<em>WomanMapper</em> and <em>ManMapper</em>), that will end up being used by our <em>DoctorMapper.</em></p><p>Since our <em>PatientsMapper </em>will need to use the <em>WomanMapper</em> and <em>ManMapper</em>, instead of creating an Interface, we need to create an Abstract class:</p><pre>@Mapper(componentModel = &quot;spring&quot;)<br>public abstract class PatientsMapper {<br><br>   @Autowired<br>   <strong>private ManMapper manMapper;</strong><br><br>   @Autowired<br>   <strong>private WomanMapper womanMapper;<br></strong><br>   public PatientsDto toDto(List&lt;Patient&gt; patients) {<br>      PatientsDto patientsDto = new PatientsDto();<br>      for (Patient patient : patients) {<br>         if (patient instanceof Man) {<br>            patientsDto.addMan(<br>                  <strong>manMapper.toDto((Man) patient))</strong>;<br>         } else if (patient instanceof Woman) {<br>            patientsDto.addWoman(<br>                  <strong>womanMapper.toDto((Woman) patient))</strong>;<br>         }<br>      }<br>      return patientsDto;<br>   }<br>}</pre><p>Finally, to make our <em>DoctorMapper </em>use the <em>PatientsMapper</em>, we need to add some configuration:</p><pre>@Mapper(<br>      componentModel = &quot;spring&quot;,<br>            unmappedTargetPolicy = ReportingPolicy.<em>ERROR</em>,<br>      <strong>uses</strong> = {AddressMapper.class, <strong>PatientsMapper.class</strong>})<br>public interface DoctorMapper {<br>   ...<br>}</pre><p>As the <em>patients</em> variable has the same name on the Entity and Dto classes, we don&#39;t need to specify anything else.</p><p>This will be the end result of the generated classes:</p><pre>@Component<br>public class DoctorMapperImpl implements DoctorMapper {<br><br>   @Autowired<br>   private AddressMapper addressMapper;<br>   <strong>@Autowired<br>   private PatientsMapper patientsMapper;</strong><br><br>   @Override<br>   public DoctorDto toDto(Doctor doctor, List&lt;City&gt; cities) {<br>      if (doctor == null) {<br>         return null;<br>      }<br><br>      DoctorDto doctorDto = new DoctorDto();<br><br>      doctorDto.setNumPatients(<br>            getNumPatients(doctor.getPatients()));<br>      doctorDto.setCityName(<br>            getCityName(doctor.getCityId(), cities));<br>      doctorDto.setSpecialityName(doctorSpecialityName(doctor));<br>      doctorDto.setContact(doctor.getPhone());<br>      doctorDto.setId(doctor.getId());<br>      doctorDto.setName(doctor.getName());<br>      doctorDto.setAddress(<br>            addressMapper.toDto(doctor.getAddress()));<br>      <strong>doctorDto.setPatients(<br>            patientsMapper.toDto(doctor.getPatients()));</strong><br><br>      return doctorDto;<br>   }<br>  ...<br>}</pre><pre>@Component<br>public class ManMapperImpl implements ManMapper {<br><br>    @Override<br>    public ManDto toDto(Man man) {<br>        if ( man == null ) {<br>            return null;<br>        }<br><br>        ManDto manDto = new ManDto();<br><br>        manDto.setId( man.getId() );<br>        manDto.setName( man.getName() );<br>        manDto.setAge( man.getAge() );<br><br>        return manDto;<br>    }<br>}</pre><pre>@Component<br>public class WomanMapperImpl implements WomanMapper {<br><br>    @Override<br>    public WomanDto toDto(Woman woman) {<br>        if ( woman == null ) {<br>            return null;<br>        }<br><br>        WomanDto womanDto = new WomanDto();<br><br>        womanDto.setId( woman.getId() );<br>        womanDto.setName( woman.getName() );<br>        womanDto.setAge( woman.getAge() );<br><br>        return womanDto;<br>    }<br>}</pre><h3>Updates</h3><p>Mapstruct also provides an easy way to handle updates. If we want to update our <strong>Doctor</strong> entity with the information on <strong>DoctorDto</strong>, we just need to create:</p><pre>@Mapping(source = &quot;contact&quot;, target = &quot;phone&quot;)<br>@Mapping(source = &quot;specialityName&quot;, target = &quot;speciality.name&quot;)<br>void updateEntity(DoctorDto doctorDto, <br>                  @MappingTarget Doctor doctor);</pre><p>As we can see on the generated implementation, it will map all variables (null or not null):</p><pre>@Override<br>public void updateEntity(DoctorDto doctorDto, Doctor doctor) {<br>    if ( doctorDto == null ) {<br>        return;<br>    }<br><br>    if ( doctor.getSpeciality() == null ) {<br>        doctor.setSpeciality( new Speciality() );<br>    }<br>    doctorDtoToSpeciality( doctorDto, doctor.getSpeciality() );<br>    doctor.setPhone( doctorDto.getContact() );<br>    doctor.setId( doctorDto.getId() );<br>    doctor.setName( doctorDto.getName() );<br>    if ( doctorDto.getAddress() != null ) {<br>        if ( doctor.getAddress() == null ) {<br>            doctor.setAddress( new Address() );<br>        }<br>        addressDtoToAddress( doctorDto.getAddress(), doctor.getAddress() );<br>    }<br>    else {<br>        doctor.setAddress( null );<br>    }<br>}</pre><h3>Patch Updates</h3><p>As we have seen in the previous example, the default update method will map every property, even if it is null. So if you encounter yourself in a situation where you just want to perform a patch update (only update the not null values), you need to use the <em>nullValuePropertyMappingStrategy</em>:</p><pre><strong>@BeanMapping(nullValuePropertyMappingStrategy = <br>      NullValuePropertyMappingStrategy.<em>IGNORE</em>)</strong><br>@Mapping(source = &quot;contact&quot;, target = &quot;phone&quot;)<br>@Mapping(source = &quot;specialityName&quot;, target = &quot;speciality.name&quot;)<br>void updatePatchEntity(DoctorDto doctorDto,<br>                       @MappingTarget Doctor doctor);</pre><p>The generated method will perform null checks before updating the values:</p><pre>@Override<br>public void updatePatchEntity(DoctorDto doctorDto, Doctor doctor) {<br>    if ( doctorDto == null ) {<br>        return;<br>    }<br><br>    if ( doctorDto.getContact() != null ) {<br>        doctor.setPhone( doctorDto.getContact() );<br>    }<br>    doctor.setId( doctorDto.getId() );<br>    if ( doctorDto.getName() != null ) {<br>        doctor.setName( doctorDto.getName() );<br>    }<br>    if ( doctorDto.getAddress() != null ) {<br>        if ( doctor.getAddress() == null ) {<br>            doctor.setAddress( new Address() );<br>        }<br>        addressDtoToAddress(<br>                doctorDto.getAddress(),<br>                doctor.getAddress() );<br>    }<br>    if ( doctor.getSpeciality() == null ) {<br>        doctor.setSpeciality( new Speciality() );<br>    }<br>    doctorDtoToSpeciality1( doctorDto, doctor.getSpeciality() );<br>}</pre><h3>Conclusion</h3><p>This article described how to take advantage of the Mapstruct library to significantly reduce our boilerplate code in a safe and elegant way.</p><p>As seen in the examples, Mapstruct offers a vast set of functionalities and configurations which allows us to create from basic to complex mappers in an easy and fast way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ddd8dac3d6d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/uphill-engineering-design/deep-dive-into-mapstruct-spring-7ddd8dac3d6d">Deep dive into Mapstruct @ Spring</a> was originally published in <a href="https://medium.com/uphill-engineering-design">UpHill Health | Engineering &amp; Design</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>