spring-attic / spring-cloud-gcp

Integration for Google Cloud Platform APIs with Spring
Apache License 2.0
704 stars 694 forks source link

Error converting String to Enum #2567

Closed beunick closed 3 years ago

beunick commented 3 years ago

Hello I am new with Sprintboot/Data Store I am not sure if this is a bug or if there is something I am not doing right.

Here is the entity: `

 @Entity
 public class account {
     private Key key;
  private AppTimeZone timeZone;
  private String name;
}   

` The Enum:

`

public enum AppTimeZone {
    AMERICA_ADAK("America/Adak");
    AMERICA_ATKA("America/Atka");
    public static AppTimeZone fromString(String str) {
        return EnumUtils.fromString(AppTimeZone.class, str);
    }}

`

The converter: `

public class AppTimeZoneConverter {
static final Converter<AppTimeZone, String> TZ_STRING_CONVERTER =
     new Converter<AppTimeZone, String>() {
    @Override
    public String convert(AppTimeZone type) {
     return type.toString();
    }};
static final Converter<String, AppTimeZone> STRING_TZ_CONVERTER =
  new Converter<String, AppTimeZone>() {
    @Override
    public AppTimeZone convert(String AppTimeZone) {
      return AppTimeZone.fromString(AppTimeZone); 
  }};
}

`

The Repository: `

@Repository
public interface AccountRepository extends DatastoreRepository<Account, Key> {
     Account findById(Key key);
}

` In my service I am doing this:

'

Account account = this.accountRepository.findById(keyObject);

'

Here is the error message I get, it looks like the mapping is not working when fetching the data:

`

org.springframework.cloud.gcp.data.datastore.core.mapping.DatastoreDataException: Unable to convert class java.lang.String to class co.app.project.common.constants.AppTimeZone at org.springframework.cloud.gcp.data.datastore.core.convert.TwoStepsConversions.convertOnReadSingle(TwoStepsConversions.java:239) ~[spring-cloud-gcp-data-datastore-1.2.5.RELEASE.jar:1.2.5.RELEASE]

`

What surprise me the most is, when I create a new object or save an existing object like this:

Account account = this.accountRepository.save(accountObject); I don't have any error on the save, the mapping works very well.

Can you please let know what's wrong ? Thank You.

beunick commented 3 years ago

Very sorry for this long message. I figure out my issue. In the Enum in the fromString() method I replace: this line: EnumUtils.fromString(AppTimeZone.class, str); With this line: for(AppTimeZone tz: AppTimeZone.values()) { if(tz.timeZone.equalsIgnoreCase(str)) { return tz; } } return null;

It works fine now. Once again sorry. I am new to datastore/springboot, not used to converter etc... Thanks for doing this. It is no easy to integrate DataStore to existing Sprintboot application because of your work. I will now close this. Thanks

dmitry-s commented 3 years ago

@beunick enum conversion is supported out of the box. I think you don't need to create your own converter for your enum.