{"id":326892,"date":"2023-09-07T03:02:02","date_gmt":"2023-09-07T03:02:02","guid":{"rendered":"https:\/\/www.baeldung.com\/java-mapstruct-bean-types-conditional"},"modified":"2023-09-07T03:02:02","modified_gmt":"2023-09-07T03:02:02","slug":"how-to-use-conditional-mapping-with-mapstruct","status":"publish","type":"post","link":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/2023\/09\/07\/how-to-use-conditional-mapping-with-mapstruct\/","title":{"rendered":"How to Use Conditional Mapping With MapStruct"},"content":{"rendered":"<p class=\"syndicated-attribution\"><meta name= \\\"keywords \\\" content= \\\"\u96fb\u5b50\u8a08\u7b97\u6a5f, \u6559\u80b2, IT \u96fb\u8166\u73ed,\u96fb\u8166\u88dc\u7fd2\uff0c \u96fb\u8166\u73ed\uff0c \u5bb6\u6559\uff0c \u79c1\u4eba\u8001\u5e2b\uff0c \u8cc7\u8a0a\u6280\u8853\uff0c \u7a0b\u5e8f\u8a2d\u8a08\uff0c \u96fb\u5b50\u8a08\u7b97\u6a5f\uff0c \u904a\u6232\uff0c \u860b\u679c\uff0c \u96fb\u5f71\uff0c \u8a08\u7b97\u6a5f\uff0c\u7de8\u78bc\uff0c Java\uff0c C\/C++\uff0c JavaScript\uff0c PHP\uff0c HTML\uff0c CSS\uff0c MySQL\uff0c mobile\uff0c Android\uff0c \u52d5\u6f2b\uff0c Python\uff0c teacher\uff0c \u88dc\u7fd2\uff0c \u96fb\u8166\u88dc\u7fd2 \u8cc7\u8a0a, \u7535\u5b50\u8ba1\u7b97\u673a, IT ,Game, apple, movie, Computer,student,Java,\u6559\u80b2, ,\u5b66\u751f, \u5b66\u4e60, learn, \u6559\u5b66,  Android, apple,anime, animation, \u4fe1\u606f\u6280\u672f, \u7a0b\u5e8f\u8bbe\u8ba1, \u79fb\u52a8\u7535\u8bdd, \u8cc7\u8a0a\u79d1\u6280,Game, Jeu, Juego,Call Of Duty ,\u4f7f\u547d\u53ec\u559a , \u6e38\u620f, \u7535\u5b50\u6e38\u620f,, \u591a\u4eba\u7535\u5b50\u6e38\u620f, \u7f51\u7edc\u6e38\u620f\uff0conline\uff0conline game, \u624b\u673a\u6e38\u620f, mobile \\\"><\/p>\n<p><img src=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-4-Featured-1024x536.png\" class=\"webfeedsFeaturedVisual wp-post-image\" alt=\"\" decoding=\"async\" loading=\"lazy\" style=\"float: left; margin-right: 5px;\" srcset=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-4-Featured-1024x536.png 1024w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-4-Featured-300x157.png 300w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-4-Featured-768x402.png 768w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-4-Featured-100x52.png 100w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-4-Featured.png 1200w\" sizes=\"(max-width: 580px) 100vw, 580px\" \/><\/p>\n<h2 id=\"bd-introduction\" data-id=\"introduction\">1. Introduction<\/h2>\n<div class=\"bd-anchor\" id=\"introduction\"><\/div>\n<p><strong><a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/mapstruct\">MapStruct<\/a> is a code generation tool that simplifies mapping between Java bean types.<\/strong> In this article, we&#8217;ll explore how to use conditional mapping with MapStruct and look at different configurations to achieve it.<\/p>\n<h2 id=\"bd-conditional-mapping-with-mapstruct\" data-id=\"conditional-mapping-with-mapstruct\">2. Conditional Mapping With MapStruct<\/h2>\n<div class=\"bd-anchor\" id=\"conditional-mapping-with-mapstruct\"><\/div>\n<p>When mapping data between objects, we often find the need to map an attribute based on certain conditions, MapStruct offers a few configuration options to achieve this.<\/p>\n<p>Let&#8217;s examine an instance of a target <em>License<\/em> object that requires mapping attributes based on a few conditions:<\/p>\n<pre><code class=\"language-java\">public class License {\r\n    private UUID id;\r\n    private OffsetDateTime startDate;\r\n    private OffsetDateTime endDate;\r\n    private boolean active;\r\n    private boolean renewalRequired;\r\n    \/\/ getters and setters\r\n}<\/code><\/pre>\n<p>The input <em>LicenseDto<\/em> contains an optional <em>startDate<\/em> and <em>endDate<\/em>:<\/p>\n<pre><code class=\"language-java\">public class LicenseDto {\r\n    private UUID id;\r\n    private LocalDateTime startDate;\r\n    private LocalDateTime endDate;\r\n    \/\/ getters and setters\r\n}<\/code><\/pre>\n<p>The mapping rules from <em>LicenseDto<\/em>\u00a0to <em>License <\/em>are:<\/p>\n<ul>\n<li><em>startDate<\/em> &#8211; If the input <em>LicenseDto<\/em> doesn&#8217;t have <em>startDate<\/em> in the request, let&#8217;s set <em>startDate<\/em> as the current date<\/li>\n<li><em>endDate<\/em> &#8211; If the input <em>LicenseDto<\/em> doesn&#8217;t have <em>endDate<\/em> in the request, let&#8217;s set <em>endDate<\/em> as one year from the current date<\/li>\n<li><em>active<\/em> &#8211; If the <em>endDate<\/em> is in the future, we will set this to <em>true<\/em><\/li>\n<li><em>renewalRequired<\/em> &#8211; If the <em>endDate<\/em> is in the next two weeks, we will set this to <em>true<\/em><\/li>\n<\/ul>\n<p>Let&#8217;s explore some of the ways we can achieve this by using the configurations provided by MapStruct.<\/p>\n<h3 id=\"bd-1-using-expressions\" data-id=\"1-using-expressions\">2.1. Using Expressions<\/h3>\n<div class=\"bd-anchor\" id=\"1-using-expressions\"><\/div>\n<p><strong>MapStruct provides the capability to use any valid Java expression inside a mapping <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/mapstruct.org\/documentation\/stable\/api\/org\/mapstruct\/Mapping.html#expression()\">expression<\/a> to generate the mapping.<\/strong> Let&#8217;s utilize this feature to map <em>startDate<\/em>:<\/p>\n<pre><code class=\"language-java\">@Mapping(target = &quot;startDate&quot;, expression = &quot;java(mapStartDate(licenseDto))&quot;)\r\nLicense toLicense(LicenseDto licenseDto);<\/code><\/pre>\n<p>We can now define the method <em>mapStartDate<\/em>:<\/p>\n<pre><code class=\"language-java\">default OffsetDateTime mapStartDate(LicenseDto licenseDto) {\r\n    return licenseDto.getStartDate() != null ? \r\n      licenseDto.getStartDate().atOffset(ZoneOffset.UTC) : OffsetDateTime.now();\r\n}<\/code><\/pre>\n<p>On compilation, MapStruct generates the code:<\/p>\n<pre><code class=\"language-java\">@Override\r\npublic License toLicense(LicenseDto licenseDto) {\r\n    License license = new License();\r\n    license.setStartDate( mapStartDate(licenseDto) );\r\n    \r\n    \/\/ Rest of generated mapping...\r\n    return license;\r\n}<\/code><\/pre>\n<p>Alternatively, without using this method, the ternary operation inside the method can be directly passed into the <em>expression<\/em> as it&#8217;s a valid Java expression.<\/p>\n<h3 id=\"bd-2-using-conditional-expressions\" data-id=\"2-using-conditional-expressions\">2.2. Using Conditional Expressions<\/h3>\n<div class=\"bd-anchor\" id=\"2-using-conditional-expressions\"><\/div>\n<p>Similar to an expression, a <strong><a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/mapstruct.org\/documentation\/stable\/api\/org\/mapstruct\/Mapping.html#conditionExpression()\">condition expression<\/a> is a feature in MapStruct that allows the mapping of an attribute based on a conditional expression inside a string as Java code.<\/strong> The generated code contains the condition inside an <em>if<\/em> block, Therefore, let&#8217;s utilize this feature to map <em>renewalRequired<\/em> in the <em>License<\/em>:<\/p>\n<pre><code class=\"language-java\">@Mapping(target = &quot;renewalRequired&quot;, conditionExpression = &quot;java(isEndDateInTwoWeeks(licenseDto))&quot;, source = &quot;.&quot;)\r\nLicense toLicense(LicenseDto licenseDto);<\/code><\/pre>\n<p>We can pass in any valid Java boolean expression inside the <em>java()<\/em> method. Let&#8217;s define the <em>isEndDateInTwoWeeks<\/em> method inside the mapper interface:<\/p>\n<pre><code class=\"language-java\">default boolean isEndDateInTwoWeeks(LicenseDto licenseDto) {\r\n    return licenseDto.getEndDate() != null \r\n       &amp;&amp; Duration.between(licenseDto.getEndDate(), LocalDateTime.now()).toDays() &lt;= 14;\r\n}<\/code><\/pre>\n<p>On compile, MapStruct generates the code to set <em>renewalRequired<\/em> if this condition is satisfied:<\/p>\n<pre><code class=\"language-java\">@Override\r\npublic License toLicense(LicenseDto licenseDto) {\r\n    License license = new License();\r\n    if ( isEndDateInTwoWeeks(licenseDto) ) {\r\n        license.setRenewalRequired( isEndDateInTwoWeeks( licenseDto ) );\r\n    }\r\n    \r\n    \/\/ Rest of generated mapping...\r\n    return license;\r\n}<\/code><\/pre>\n<p>It&#8217;s also possible to set the value of an attribute from the source when a condition matches. In such instances, the mapper will populate the desired attribute with the corresponding value from the source.<\/p>\n<h3 id=\"bd-3-using-beforeafter-mapping\" data-id=\"3-using-beforeafter-mapping\">2.3. Using Before\/After Mapping<\/h3>\n<div class=\"bd-anchor\" id=\"3-using-beforeafter-mapping\"><\/div>\n<p><strong>In certain situations, if we want to modify the object before or after mapping through customization, we can make use of the <em>@BeforeMapping<\/em> and <em>@AfterMapping<\/em> annotations from MapStruct<\/strong>. Let&#8217;s use this feature to map <em>endDate<\/em>:<\/p>\n<pre><code class=\"language-java\">@Mapping(target = &quot;endDate&quot;, ignore = true)\r\nLicense toLicense(LicenseDto licenseDto);<\/code><\/pre>\n<p>We can define the <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/mapstruct.org\/documentation\/stable\/api\/org\/mapstruct\/AfterMapping.html\"><em>AfterMapping<\/em><\/a> annotation to map <em>endDate<\/em> conditionally. In this way, we can control the mapping based on specific conditions:<\/p>\n<pre><code class=\"language-java\">@AfterMapping\r\ndefault void afterMapping(LicenseDto licenseDto, @MappingTarget License license) {\r\n    OffsetDateTime endDate = licenseDto.getEndDate() != null ? licenseDto.getEndDate()\r\n      .atOffset(ZoneOffset.UTC) : OffsetDateTime.now()\r\n      .plusYears(1);\r\n    license.setEndDate(endDate);\r\n}<\/code><\/pre>\n<p>We need to pass both the input <em>LicenseDto<\/em> and the target <em>License<\/em> object as parameters to this <em>afterMapping<\/em> method. Consequently, this ensures that MapStruct generates the code that invokes this method as a final step of mapping, before returning the <em>License<\/em> object:<\/p>\n<pre><code class=\"language-java\">@Override\r\npublic License toLicense(LicenseDto licenseDto) {\r\n    License license = new License();\r\n    \/\/ Rest of generated mapping...\r\n    afterMapping( licenseDto, license );\r\n    return license;\r\n}<\/code><\/pre>\n<p>Alternatively, we can use the <em>BeforeMapping<\/em> annotation instead to achieve the same result.<\/p>\n<h2 id=\"bd-conclusion\" data-id=\"conclusion\">3. Conclusion<\/h2>\n<div class=\"bd-anchor\" id=\"conclusion\"><\/div>\n<p>In this article, we explored different ways to map attributes between Java bean types conditionally using MapStruct.<\/p>\n<p>As always, the source code for the examples is available\u00a0<a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/github.com\/eugenp\/tutorials\/tree\/master\/mapstruct\">over on GitHub<\/a>.<\/p>\n<p><Img align=\"left\" border=\"0\" height=\"1\" width=\"1\" alt=\"\" style=\"border:0;float:left;margin:0;padding:0;width:1px!important;height:1px!important;\" hspace=\"0\" src=\"https:\/\/feeds.feedblitz.com\/~\/i\/792614726\/0\/baeldung\"><\/p>\n<div style=\"clear:both;padding-top:0.2em;\"><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/792614726\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/fblike20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Pin it!\" href=\"https:\/\/feeds.feedblitz.com\/_\/29\/792614726\/baeldung,https%3A%2F%2Fwww.baeldung.com%2Fwp-content%2Fuploads%2F2021%2F09%2FJava-4-Featured-1024x536.png\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/pinterest20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Tweet This\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/792614726\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/twitter20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/792614726\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/email20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Subscribe by RSS\" href=\"https:\/\/feeds.feedblitz.com\/_\/20\/792614726\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/rss20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a rel=\"NOFOLLOW\" title=\"View Comments\" href=\"https:\/\/www.baeldung.com\/java-mapstruct-bean-types-conditional#respond\"><img decoding=\"async\" height=\"20\" style=\"border:0;margin:0;padding:0;\" src=\"https:\/\/assets.feedblitz.com\/i\/comments20.png\"><\/a>&#160;<a title=\"Follow Comments via RSS\" href=\"https:\/\/www.baeldung.com\/java-mapstruct-bean-types-conditional\/feed\"><img decoding=\"async\" height=\"20\" style=\"border:0;margin:0;padding:0;\" src=\"https:\/\/assets.feedblitz.com\/i\/commentsrss20.png\"><\/a>&#160;<\/div>\n\n<p class=\"syndicated-attribution\"><figure class= \\\"wp-block-image alignnone \\\"><img src= \\\"http:\/\/itteacheritfreelance.hk\/test\/wordpress\/wp-content\/uploads\/2016\/05\/logo2-2.png\\\" alt=\\\"IT\u96fb\u8166\u88dc\u7fd2 java\u88dc\u7fd2 \u70ba\u5927\u5bb6\u914d\u5c0d\u96fb\u8166\u88dc\u7fd2,IT freelance, \u79c1\u4eba\u8001\u5e2b, PHP\u88dc\u7fd2,CSS\u88dc\u7fd2,XML,Java\u88dc\u7fd2,MySQL\u88dc\u7fd2,graphic design\u88dc\u7fd2,\u4e2d\u5c0f\u5b78ICT\u88dc\u7fd2,\u4e00\u5c0d\u4e00\u79c1\u4eba\u88dc\u7fd2\u548cFreelance\u81ea\u7531\u5de5\u4f5c\u914d\u5c0d\u3002\\\"\/><figcaption>\u7acb\u523b\u8a3b\u518a\u53ca\u5831\u540d\u96fb\u8166\u88dc\u7fd2\u8ab2\u7a0b\u5427!<\/figcaption><\/figure>\r\n<\/br>Find A Teacher Form:\r\n<\/br>https:\/\/docs.google.com\/forms\/d\/1vREBnX5n262umf4wU5U2pyTwvk9O-JrAgblA-wH9GFQ\/viewform?edit_requested=true#responses\r\n<\/br><\/br>Email:\r\n<\/br>public1989two@gmail.com<br><br><br><br><br><br><br>\r\n<a href=www.itsec.hk style=color:#FFFFFF;>www.itsec.hk<\/a><br>\r\n<a href=\\\"www.itsec.vip\\\" style=color:#FFFFFF;>www.itsec.vip<\/a><br>\r\n<a href=\\\"www.itseceu.uk\\\" style=color:#FFFFFF;>www.itseceu.uk<\/a><br><\/p>","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p><img decoding=\"async\" src=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-4-Featured-1024x536.png\" class=\"webfeedsFeaturedVisual wp-post-image\" alt=\"\" loading=\"lazy\"><\/p>\n<p>Learn how to set fields based on conditions when mapping between Java bean types with MapStruct.<\/p>\n<div><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/792614726\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/fblike20.png\"><\/a>\u00a0<a title=\"Pin it!\" href=\"https:\/\/feeds.feedblitz.com\/_\/29\/792614726\/baeldung,https%3A%2F%2Fwww.baeldung.com%2Fwp-content%2Fuploads%2F2021%2F09%2FJava-4-Featured-1024x536.png\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/pinterest20.png\"><\/a>\u00a0<a title=\"Tweet This\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/792614726\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/twitter20.png\"><\/a>\u00a0<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/792614726\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/email20.png\"><\/a>\u00a0<a title=\"Subscribe by RSS\" href=\"https:\/\/feeds.feedblitz.com\/_\/20\/792614726\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/rss20.png\"><\/a>\u00a0<a rel=\"NOFOLLOW\" title=\"View Comments\" href=\"https:\/\/www.baeldung.com\/java-mapstruct-bean-types-conditional#respond\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/comments20.png\"><\/a>\u00a0<a title=\"Follow Comments via RSS\" href=\"https:\/\/www.baeldung.com\/java-mapstruct-bean-types-conditional\/feed\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/commentsrss20.png\"><\/a>\u00a0<\/div>\n<\/div>","protected":false},"author":1979,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"slim_seo":{"title":"How to Use Conditional Mapping With MapStruct - ITTeacherITFreelance.hk","description":"Learn how to set fields based on conditions when mapping between Java bean types with MapStruct. \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0"},"footnotes":""},"categories":[6,1307],"tags":[10566],"_links":{"self":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/326892"}],"collection":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/users\/1979"}],"replies":[{"embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/comments?post=326892"}],"version-history":[{"count":1,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/326892\/revisions"}],"predecessor-version":[{"id":326893,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/326892\/revisions\/326893"}],"wp:attachment":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/media?parent=326892"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/categories?post=326892"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/tags?post=326892"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}