{"id":418189,"date":"2024-06-30T02:01:40","date_gmt":"2024-06-30T02:01:40","guid":{"rendered":"http:\/\/savepearlharbor.com\/?p=418189"},"modified":"-0001-11-30T00:00:00","modified_gmt":"2024-06-30T02:01:40","slug":"","status":"publish","type":"post","link":"https:\/\/savepearlharbor.com\/?p=418189","title":{"rendered":"<span>Spring Data JPA entity enum converter<\/span>"},"content":{"rendered":"<div><!--[--><!--]--><\/div>\n<div id=\"post-content-body\">\n<div>\n<div class=\"article-formatted-body article-formatted-body article-formatted-body_version-2\">\n<div xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n<figure class=\"full-width\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/habrastorage.org\/r\/w780q1\/getpro\/habr\/upload_files\/97f\/e49\/a16\/97fe49a168170322409d3f16fc20f1bf.jpeg\" alt=\"Want an entity enum converter!?\" title=\"Want an entity enum converter!?\" width=\"1920\" height=\"1200\" data-src=\"https:\/\/habrastorage.org\/getpro\/habr\/upload_files\/97f\/e49\/a16\/97fe49a168170322409d3f16fc20f1bf.jpeg\" data-blurred=\"true\"\/><\/p>\n<div><figcaption>Want an entity enum converter!?<\/figcaption><\/div>\n<\/figure>\n<p>Faced with situation when had to map <strong><em>STRING VALUE<\/em><\/strong> coming from database <strong><em>TO ENUM<\/em><\/strong>. The problem happens when value stored in database differs from enum name. And here we need a workaround to make a mapping. I will describe main points on how I was able to realize it.<\/p>\n<hr\/>\n<blockquote>\n<p><strong><em>AttributeConverter<\/em> can be used to convert an entity attribute to a database value and vice versa!<\/strong><\/p>\n<\/blockquote>\n<p>If you ever worked with Java enums in JPA you are definitely aware of their limitations and traps. Using Enum as a property of your\u00a0@<strong><em>Entity<\/em><\/strong>\u00a0is often very good choice, however JPA prior to 2.1 didn\u2019t handle them very well.<\/p>\n<p><strong><em>Dependencies<\/em> <\/strong>needed for this case are below. You can adjust versions and scopes with regards to your project case and dependency requirements.<\/p>\n<pre><code class=\"xml\">        &lt;dependency>             &lt;groupId>org.springframework.data&lt;\/groupId>             &lt;artifactId>spring-data-jpa&lt;\/artifactId>         &lt;\/dependency>          &lt;dependency>             &lt;groupId>io.projectreactor&lt;\/groupId>             &lt;artifactId>reactor-core&lt;\/artifactId>         &lt;\/dependency>          &lt;dependency>             &lt;groupId>org.projectlombok&lt;\/groupId>             &lt;artifactId>lombok&lt;\/artifactId>         &lt;\/dependency>          &lt;dependency>             &lt;groupId>org.hibernate&lt;\/groupId>             &lt;artifactId>hibernate-entitymanager&lt;\/artifactId>         &lt;\/dependency><\/code><\/pre>\n<p>Now let&#8217;s introduce <strong>AttributeConverter<\/strong> interface implementation to be able to write our own realization of mapping. Contract contains 2 methods:<\/p>\n<ol>\n<li>\n<p><strong><em>convertToDatabaseColumn<\/em><\/strong> &#8212; to get String from Enum;<\/p>\n<\/li>\n<li>\n<p><strong><em>convertToEntityAttribute<\/em><\/strong> &#8212; to get Enum from String.<\/p>\n<\/li>\n<\/ol>\n<pre><code class=\"java\">import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import reactor.core.publisher.Flux;  import javax.persistence.AttributeConverter; import java.util.concurrent.atomic.AtomicReference;  @Slf4j public class OperationTypeConverter implements AttributeConverter&lt;OperationType, String> { \/\/ need to implement AttributeConverter interface       @Override     public String convertToDatabaseColumn(@NonNull OperationType operation) { \/\/ Lombok @NonNull to prevent NPE         return operation.getOperationType(); \/\/ get operation type as STRING from enum      }      @Override     public OperationType convertToEntityAttribute(@NonNull String operationType) { \/\/ Lombok @NonNull to prevent NPE                  Flux&lt;OperationType> operationTypes = Flux.just(OperationType.values()); \/\/ start Flux of all string values from enum for mapping           AtomicReference&lt;OperationType> mappedOperation = new AtomicReference&lt;>(); \/\/ instead of block operation on Reactive. See https:\/\/habr.com\/en\/articles\/741464\/           operationsTypes                 .parallel() \/\/ we can run in parallel here as there is no dependency of data in runtime                 .runOn(Schedulers.fromExecutor(Executors.newWorkStealingPool()))                 .filter(value -> value.getOperationType().equals(operationType)) \/\/ filter by incoming value                 .subscribe(mappedDctOperation::set, \/\/ set the mappedOperation AtomicReference field                         throwable -> { \/\/ to throw the problem                              log.error(\"Error during converter execution for operation type {}.\", operationType); \/\/ logging is important, especially on debug level                             throw new OperationTypeConverterException(throwable, operationType); \/\/ dedicated exception class                         });          return mappedOperation.get();     } }<\/code><\/pre>\n<p>In <strong><em>convertToEntityAttribute<\/em><\/strong> you can see how mapping is done via filtration by values using Spring Reactor Flux. In this case it is used parallel run, and Flux by default work in ASYNC mode. If you don&#8217;t need concurrent parallel execution you can remove these lines:<\/p>\n<blockquote>\n<p><code>.parallel()             .runOn(Schedulers.fromExecutor(Executors.newWorkStealingPool())) <\/code><\/p>\n<\/blockquote>\n<p>Removing this option will switch your <strong>Flux<\/strong> to default <strong>sequential asynchronous<\/strong> mode.<\/p>\n<blockquote>\n<p>You can also set the\u00a0<strong>AttributeConverter<\/strong> to work automatically using annotation on converter class<em>:<\/em><\/p>\n<p><strong><em>@Converter<\/em><\/strong><em>(autoApply = true)<br \/><\/em> <br \/>This way JPA will automatically apply the conversion logic to all mapped attributes of a\u00a0<strong><em>your ENUM<\/em><\/strong>\u00a0type.<\/p>\n<\/blockquote>\n<p>But in this case I put\u00a0<strong><em>@Converter<\/em><\/strong>\u00a0annotation directly on the DatabaseOperation entity&#8217;s field.<\/p>\n<p>On below screenshot you can see special <strong>ICON<\/strong> on the left bar near the class declaration. Just click on it &#8212; and IDEA will navigate you to entity in which this converter is used:<\/p>\n<figure class=\"full-width\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/habrastorage.org\/r\/w1560\/getpro\/habr\/upload_files\/fa2\/ead\/79e\/fa2ead79ef4e85d973190d084002cbaa.png\" alt=\"You can click on left ICON to open field in Entity which use this converter. \" title=\"You can click on left ICON to open field in Entity which use this converter. \" width=\"941\" height=\"79\" data-src=\"https:\/\/habrastorage.org\/getpro\/habr\/upload_files\/fa2\/ead\/79e\/fa2ead79ef4e85d973190d084002cbaa.png\"\/><\/p>\n<div><figcaption>You can click on left ICON to open field in Entity which use this converter. <\/figcaption><\/div>\n<\/figure>\n<p><strong><em>OperationType<\/em><\/strong> enum contains 2 options. Important! Name of ENUM not matches to value which stored in database. And here our converter comes to help us in mapping between DB and ENUM!<\/p>\n<pre><code class=\"java\">import lombok.AllArgsConstructor; import lombok.Getter;  @Getter @AllArgsConstructor public enum OperationType {      READ(\"optimized read\"),     WRITE(\"turbo write\");        private final String operationType; }<\/code><\/pre>\n<p><strong><em>DatabaseOperation<\/em><\/strong> entity contains <strong><em>operationType<\/em><\/strong><em> <\/em>field on which we will enable our functional of AttributeConverter<em>. <\/em>To enable it &#8212; just put annotation<em> @<\/em><strong><em>Converter<\/em>(converter = OperationTypeConverter.class)<\/strong> on field.<\/p>\n<pre><code class=\"java\">import lombok.*; import org.hibernate.Hibernate;  import javax.persistence.*; import java.util.Objects;  @Getter @Setter @ToString @NoArgsConstructor @Entity @Table public class DatabaseOperation {      @Id     @Column     private Long id;      \/\/ rest fields...        @Column     @Convert(converter = OperationTypeConverter.class) \/\/ to enable our AttributeConverter     private OperationType operationType; \/\/ the golden field :)      @Override     public boolean equals(Object o) { \/\/ safe reazation of equals for entity         if (this == o) return true;         if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;         DatabaseOperation that = (DatabaseOperation) o;         return Objects.equals(id, that.id);     }      @Override     public int hashCode() { \/\/ safe reazation of hashCode for entity         return getClass().hashCode();     } }<\/code><\/pre>\n<p>Here I also override <strong>equals<\/strong> and <strong>hashCode<\/strong> to make it safe for <strong>JPA<\/strong> calls during runtime execution.<\/p>\n<hr\/>\n<p>Hope I described my case well with examples which you can use in your project.  <strong>AttributeConverter<\/strong> are really helpful thing for mapping values from DB to Java enum when working with <strong>Spring Data JPA<\/strong> and <strong>Hibernate<\/strong>. <\/p>\n<p>If you have what to say about the topic and want to give negative rating &#8212; please feel free to write your comments to understand your opinion. Otherwise it is not serious and it is not clear why you vote negatively.<\/p>\n<p>And of course If you like this article, please vote UP &#8212; this will support me to write more such posts with real code examples!<\/p>\n<\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!----><!----><\/div>\n<p><!----><!----><br \/> \u0441\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b \u0441\u0442\u0430\u0442\u044c\u0438 <a href=\"https:\/\/habr.com\/ru\/articles\/747140\/\"> https:\/\/habr.com\/ru\/articles\/747140\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<div><!--[--><!--]--><\/div>\n<div id=\"post-content-body\">\n<div>\n<div class=\"article-formatted-body article-formatted-body article-formatted-body_version-2\">\n<div xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n<figure class=\"full-width\">\n<div><figcaption>Want an entity enum converter!?<\/figcaption><\/div>\n<\/figure>\n<p>Faced with situation when had to map <strong><em>STRING VALUE<\/em><\/strong> coming from database <strong><em>TO ENUM<\/em><\/strong>. The problem happens when value stored in database differs from enum name. And here we need a workaround to make a mapping. I will describe main points on how I was able to realize it.<\/p>\n<hr\/>\n<blockquote>\n<p><strong><em>AttributeConverter<\/em> can be used to convert an entity attribute to a database value and vice versa!<\/strong><\/p>\n<\/blockquote>\n<p>If you ever worked with Java enums in JPA you are definitely aware of their limitations and traps. Using Enum as a property of your\u00a0@<strong><em>Entity<\/em><\/strong>\u00a0is often very good choice, however JPA prior to 2.1 didn\u2019t handle them very well.<\/p>\n<p><strong><em>Dependencies<\/em> <\/strong>needed for this case are below. You can adjust versions and scopes with regards to your project case and dependency requirements.<\/p>\n<pre><code class=\"xml\">        &lt;dependency>             &lt;groupId>org.springframework.data&lt;\/groupId>             &lt;artifactId>spring-data-jpa&lt;\/artifactId>         &lt;\/dependency>          &lt;dependency>             &lt;groupId>io.projectreactor&lt;\/groupId>             &lt;artifactId>reactor-core&lt;\/artifactId>         &lt;\/dependency>          &lt;dependency>             &lt;groupId>org.projectlombok&lt;\/groupId>             &lt;artifactId>lombok&lt;\/artifactId>         &lt;\/dependency>          &lt;dependency>             &lt;groupId>org.hibernate&lt;\/groupId>             &lt;artifactId>hibernate-entitymanager&lt;\/artifactId>         &lt;\/dependency><\/code><\/pre>\n<p>Now let&#8217;s introduce <strong>AttributeConverter<\/strong> interface implementation to be able to write our own realization of mapping. Contract contains 2 methods:<\/p>\n<ol>\n<li>\n<p><strong><em>convertToDatabaseColumn<\/em><\/strong> &#8212; to get String from Enum;<\/p>\n<\/li>\n<li>\n<p><strong><em>convertToEntityAttribute<\/em><\/strong> &#8212; to get Enum from String.<\/p>\n<\/li>\n<\/ol>\n<pre><code class=\"java\">import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import reactor.core.publisher.Flux;  import javax.persistence.AttributeConverter; import java.util.concurrent.atomic.AtomicReference;  @Slf4j public class OperationTypeConverter implements AttributeConverter&lt;OperationType, String> { \/\/ need to implement AttributeConverter interface       @Override     public String convertToDatabaseColumn(@NonNull OperationType operation) { \/\/ Lombok @NonNull to prevent NPE         return operation.getOperationType(); \/\/ get operation type as STRING from enum      }      @Override     public OperationType convertToEntityAttribute(@NonNull String operationType) { \/\/ Lombok @NonNull to prevent NPE                  Flux&lt;OperationType> operationTypes = Flux.just(OperationType.values()); \/\/ start Flux of all string values from enum for mapping           AtomicReference&lt;OperationType> mappedOperation = new AtomicReference&lt;>(); \/\/ instead of block operation on Reactive. See https:\/\/habr.com\/en\/articles\/741464\/           operationsTypes                 .parallel() \/\/ we can run in parallel here as there is no dependency of data in runtime                 .runOn(Schedulers.fromExecutor(Executors.newWorkStealingPool()))                 .filter(value -> value.getOperationType().equals(operationType)) \/\/ filter by incoming value                 .subscribe(mappedDctOperation::set, \/\/ set the mappedOperation AtomicReference field                         throwable -> { \/\/ to throw the problem                              log.error(\"Error during converter execution for operation type {}.\", operationType); \/\/ logging is important, especially on debug level                             throw new OperationTypeConverterException(throwable, operationType); \/\/ dedicated exception class                         });          return mappedOperation.get();     } }<\/code><\/pre>\n<p>In <strong><em>convertToEntityAttribute<\/em><\/strong> you can see how mapping is done via filtration by values using Spring Reactor Flux. In this case it is used parallel run, and Flux by default work in ASYNC mode. If you don&#8217;t need concurrent parallel execution you can remove these lines:<\/p>\n<blockquote>\n<p><code>.parallel()             .runOn(Schedulers.fromExecutor(Executors.newWorkStealingPool())) <\/code><\/p>\n<\/blockquote>\n<p>Removing this option will switch your <strong>Flux<\/strong> to default <strong>sequential asynchronous<\/strong> mode.<\/p>\n<blockquote>\n<p>You can also set the\u00a0<strong>AttributeConverter<\/strong> to work automatically using annotation on converter class<em>:<\/em><\/p>\n<p><strong><em>@Converter<\/em><\/strong><em>(autoApply = true)<br \/><\/em> <br \/>This way JPA will automatically apply the conversion logic to all mapped attributes of a\u00a0<strong><em>your ENUM<\/em><\/strong>\u00a0type.<\/p>\n<\/blockquote>\n<p>But in this case I put\u00a0<strong><em>@Converter<\/em><\/strong>\u00a0annotation directly on the DatabaseOperation entity&#8217;s field.<\/p>\n<p>On below screenshot you can see special <strong>ICON<\/strong> on the left bar near the class declaration. Just click on it &#8212; and IDEA will navigate you to entity in which this converter is used:<\/p>\n<figure class=\"full-width\">\n<div><figcaption>You can click on left ICON to open field in Entity which use this converter. <\/figcaption><\/div>\n<\/figure>\n<p><strong><em>OperationType<\/em><\/strong> enum contains 2 options. Important! Name of ENUM not matches to value which stored in database. And here our converter comes to help us in mapping between DB and ENUM!<\/p>\n<pre><code class=\"java\">import lombok.AllArgsConstructor; import lombok.Getter;  @Getter @AllArgsConstructor public enum OperationType {      READ(\"optimized read\"),     WRITE(\"turbo write\");        private final String operationType; }<\/code><\/pre>\n<p><strong><em>DatabaseOperation<\/em><\/strong> entity contains <strong><em>operationType<\/em><\/strong><em> <\/em>field on which we will enable our functional of AttributeConverter<em>. <\/em>To enable it &#8212; just put annotation<em> @<\/em><strong><em>Converter<\/em>(converter = OperationTypeConverter.class)<\/strong> on field.<\/p>\n<pre><code class=\"java\">import lombok.*; import org.hibernate.Hibernate;  import javax.persistence.*; import java.util.Objects;  @Getter @Setter @ToString @NoArgsConstructor @Entity @Table public class DatabaseOperation {      @Id     @Column     private Long id;      \/\/ rest fields...        @Column     @Convert(converter = OperationTypeConverter.class) \/\/ to enable our AttributeConverter     private OperationType operationType; \/\/ the golden field :)      @Override     public boolean equals(Object o) { \/\/ safe reazation of equals for entity         if (this == o) return true;         if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;         DatabaseOperation that = (DatabaseOperation) o;         return Objects.equals(id, that.id);     }      @Override     public int hashCode() { \/\/ safe reazation of hashCode for entity         return getClass().hashCode();     } }<\/code><\/pre>\n<p>Here I also override <strong>equals<\/strong> and <strong>hashCode<\/strong> to make it safe for <strong>JPA<\/strong> calls during runtime execution.<\/p>\n<hr\/>\n<p>Hope I described my case well with examples which you can use in your project.  <strong>AttributeConverter<\/strong> are really helpful thing for mapping values from DB to Java enum when working with <strong>Spring Data JPA<\/strong> and <strong>Hibernate<\/strong>. <\/p>\n<p>If you have what to say about the topic and want to give negative rating &#8212; please feel free to write your comments to understand your opinion. Otherwise it is not serious and it is not clear why you vote negatively.<\/p>\n<p>And of course If you like this article, please vote UP &#8212; this will support me to write more such posts with real code examples!<\/p>\n<\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!----><!----><\/div>\n<p><!----><!----><br \/> \u0441\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b \u0441\u0442\u0430\u0442\u044c\u0438 <a href=\"https:\/\/habr.com\/ru\/articles\/747140\/\"> https:\/\/habr.com\/ru\/articles\/747140\/<\/a><br \/><\/br><\/br><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[],"tags":[],"class_list":["post-418189","post","type-post","status-publish","format-standard","hentry"],"_links":{"self":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/418189","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=418189"}],"version-history":[{"count":0,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/418189\/revisions"}],"wp:attachment":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=418189"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=418189"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=418189"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}