Model Mapper异常:仅在Docker中无法将java.lang.String转换为java.lang.Integer。

huangapple go评论89阅读模式
英文:

Model Mapper Exception: failed to convert java.lang.String to java.lang.Integer only in Docker

问题

我在将DTO转换为实体时遇到了NumberFormatException。尽管我在DTO和实体中都使用String类型来表示该字段,但我仍然遇到了异常。

奇怪的是,只有在将我的应用部署到Docker上时,我才会遇到这个异常,如果我将应用程序作为独立应用运行,一切都正常。

以下是我的代码示例:

UserDTO:

@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserDto {
   private Integer userId;
   private String displayCode;
   // 其他字段...
   // getters和setters...
}

UserEntity:

@Entity
@Table(name = "user", schema = "user_management")
public class UserEntity extends BaseEntity implements Serializable {
   private static final long serialVersionUID = 1L;
   
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   @Column(name = "user_id")
   private Integer userId;
   @Column(name = "display_code")
   private String displayCode;
   // 其他字段...
   // getters和setters...
}

UserService类:

@Override
@Transactional
public UserDto persist(UserWithDependenciesDto user) {
    // 进行转换...
}

UserWithDependenciesDto:

public class UserWithDependenciesDto {
    private Integer partnerId;
    private UserDto user;
    private Integer createdBy;
    // 其他字段...
}

异常信息:

org.modelmapper.MappingException: ModelMapper mapping errors:
1) Converter org.modelmapper.internal.converter.NumberConverter@e822ec7 failed to convert java.lang.String to java.lang.Integer.
Caused by: org.modelmapper.MappingException: ModelMapper mapping errors:
1) Error mapping AJ01 to java.lang.Integer
1 error
at org.modelmapper.internal.Errors.toMappingException(Errors.java:258)
at org.modelmapper.internal.converter.NumberConverter.numberFor(NumberConverter.java:181)
at org.modelmapper.internal.converter.NumberConverter.convert(NumberConverter.java:75)
at org.modelmapper.internal.converter.NumberConverter.convert(NumberConverter.java:57)
// 更多异常信息...

JSON示例:

{
  "data": {
    "partnerId": 1,
    "user": {
      "userId": 0,
      "displayCode": "BC410",
      // 其他字段...
      "accessCode": "AJ01", // 这是我得到数字格式异常的地方。
      // 其他字段...
    },
    "createdBy": 1
  }
}

我在UserDto和UserEntity中的AccessCode字段上都遇到了数字格式异常。您可以看到,在两侧都使用了String类型。

英文:

I'm facing NumberFormatException when Converting DTO to Entity. Though the field on which I'm getting that exception is String in both DTO and Entity.

And the weird thing is I'm getting that exception only when I deploy my application on docker, If I run my application as standalone then everything is fine.

Below is my code

UserDTO:

@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserDto {
   private Integer userId;

   private String displayCode;

   private String firstName;

   private String lastName;

   private String username;

   private String password;

   private String email;

   private String phone;

   private String photo;

   private Short title;

   private String npi;

   private List<Integer> postNominal;

   @JsonProperty("isDoctor")
   private Boolean isDoctor;

   private Integer userType;

   private Boolean active;

   private Boolean agreementActive;

   private String accessCode;

   private Integer createdBy;

   private Timestamp createdTimestamp;

   private Integer updatedBy;

   private Timestamp updatedTimestamp;

   private List<RoleDto> roles;

   private Integer departmentId;

   private UserDto reportingTo;

   @JsonIgnore
   private String partnerDisplayCode;

   @JsonProperty("userRoles")
   private String userRole;

   private String  base64Image;

   getters...
   setters...

}

UserEntity:

 @Entity
 @Table(name = "user", schema = "user_management")
 public class UserEntity extends BaseEntity implements Serializable {
     private static final long serialVersionUID = 1L;

     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     @Column(name = "user_id")
     private Integer userId;

     @Column(name = "display_code")
     private String displayCode;

     @Column(name = "user_type")
     private Short userType;

     @Column(name = "first_name")
     private String firstName;

     @Column(name = "last_name")
     private String lastName;

     @Column(name = "username")
     private String username;

     @Column(name = "password")
     private String password;

     @Column(name = "email")
     private String email;

     @Column(name = "phone")
     private String phone;

     @Column(name = "photo")
     private String photo;

     @Column(name = "title")
     private Short title;

     @Column(name = "npi")
     private String npi;

     @Column(name = "department_id")
     private Integer departmentId;

     @Column(name = "is_doctor")
     private Short isDoctor;

     @Column(name = "agreement_active")
     private Short agreementActive;

     @Column(name = "access_code")
     private String accessCode;

     @Column(name = "status")
     private Short active;

     getters ....
     setters
 }

UserService Class:

@Override
@Transactional
public UserDto persist(UserWithDependenciesDto user) {
    modelMapper.getConfiguration().setSkipNullEnabled(true);
    modelMapper.addConverter(CommonUtil.BOOLEAN_SHORT_CONVERTER);
    UserEntity userEntity = modelMapper.map(user.getUser(), UserEntity.class);
     ....
}

@PostConstruct
public void initializeModelMapperStrategy() {
    this.modelMapper.getConfiguration().setAmbiguityIgnored(true);
    this.modelMapper.getConfiguration()
                      .setMatchingStrategy(MatchingStrategies.STRICT);
}

UserWithDependenciesDto:

 public class UserWithDependenciesDto {
      @JsonProperty("partnerId")
      private Integer partnerId;
      @JsonProperty("user")
      private  UserDto user;
      @JsonProperty("createdBy")
      private  Integer createdBy;
     .... 
 }

Exception:

org.modelmapper.MappingException: ModelMapper mapping errors:
nglis-usrm-api_1  | 
nglis-usrm-api_1  | 1) Converter org.modelmapper.internal.converter.NumberConverter@e822ec7 
failed to convert java.lang.String to java.lang.Integer.
nglis-usrm-api_1  | Caused by: org.modelmapper.MappingException: ModelMapper mapping errors:
nglis-usrm-api_1  | 
nglis-usrm-api_1  | 1) Error mapping AJ01 to java.lang.Integer
nglis-usrm-api_1  | 
nglis-usrm-api_1  | 1 error
nglis-usrm-api_1  | 	at 
org.modelmapper.internal.Errors.toMappingException(Errors.java:258)
nglis-usrm-api_1  | 	at 
org.modelmapper.internal.converter.NumberConverter.numberFor(NumberConverter.java:181)
nglis-usrm-api_1  | 	at 
org.modelmapper.internal.converter.NumberConverter.convert(NumberConverter.java:75)
nglis-usrm-api_1  | 	at 
org.modelmapper.internal.converter.NumberConverter.convert(NumberConverter.java:57)
nglis-usrm-api_1  | 	at 
org.modelmapper.internal.MappingEngineImpl.convert(MappingEngineImpl.java:303)
nglis-usrm-api_1  | 	at 
org.modelmapper.internal.MappingEngineImpl.map(MappingEngineImpl.java:110)
nglis-usrm-api_1  | 	at 
org.modelmapper.internal.MappingEngineImpl.setDestinationValue(MappingEngineImpl.java:242)
nglis-usrm-api_1  | 	at 
org.modelmapper.internal.MappingEngineImpl.propertyMap(MappingEngineImpl.java:188)
nglis-usrm-api_1  | 	at 
org.modelmapper.internal.MappingEngineImpl.typeMap(MappingEngineImpl.java:152)
nglis-usrm-api_1  | 	at 
org.modelmapper.internal.MappingEngineImpl.map(MappingEngineImpl.java:106)
nglis-usrm-api_1  | 	at 
org.modelmapper.internal.MappingEngineImpl.map(MappingEngineImpl.java:72)
nglis-usrm-api_1  | 	at org.modelmapper.ModelMapper.mapInternal(ModelMapper.java:573)
nglis-usrm-api_1  | 	at org.modelmapper.ModelMapper.map(ModelMapper.java:406)
nglis-usrm-api_1  | 	at 
com.sip.nglis.partneruser.manager.impl.UserManagerImpl.persist(UserManagerImpl.java:61)
nglis-usrm-api_1  | 	at 
com.sip.nglis.partneruser.manager.impl.UserManagerImpl$$FastClassBySpringCGLIB$$c52d9382
.invoke( 
 <generated>)
nglis-usrm-api_1  | 	at 
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
nglis-usrm-api_1  | 	at 

Json:

{
"data":{
  "partnerId":1,
  "user":{
     "userId":0,
     "displayCode":"BC410",
     "firstName":"Ikram",
     "lastName":"Sardar Khan",
     "username":"dsfsdf342423",
     "password":"dsfsdfg",
     "email":"gdfgdf423423423@siparadigm.com",
     "phone":"03456789010",
     "title":2,
     "npi":"ghgrere4234qweas",
     "postNominal":[
        1,
        2
     ],
     "userType":1,
     "active":true,
     "agreementActive":true,
     "accessCode":"AJ01",    **This is the place where I'm getting the number format exception. **
     "createdBy":1,
     "createdTimestamp":1600780421007,
     "roles":[
        {
           "createdBy":1,
           "createdTimestamp":1600640026453,
           "roleUId":2,
           "roleUType":1,
           "name":"Partner Admin",
           "status":true,
           "isSystemOnly":0,
           "isClientRole":0,
           "isPhysician":false
        },
        {
           "createdBy":1,
           "createdTimestamp":1600640026453,
           "roleUId":3,
           "roleUType":1,
           "name":"CRM",
           "status":true,
           "isSystemOnly":0,
           "isClientRole":0,
           "isPhysician":true
        }
     ],
     "isDoctor":false
  },
  "createdBy":1

}
}

I'm getting the number format exception on AccessCode in UserDto and Entity. You will see that on both sides it is String.

答案1

得分: 0

好的,这很奇怪。不知何故,模型映射器的策略从严格(Strict)变为宽松(Loose)。尽管在后置构造(post construct)阶段它的策略是严格的,但在它开始映射对象的地方,策略变成了宽松。

所以我所做的是移除了后置构造注解,并调用了进行转换的方法。因此在转换过程中,策略变为了严格,上述问题得以解决。

英文:

OK, this is very weird. Somehow model mapper was changing its strategy from Strict to Loose. though in post construct it was Strict when it reached the place where it was mapping the objects, the strategy was Loose.

So what I did was to remove the post construct annotation and call the method where conversions are happening. So during conversion, the strategy became strict and the above issue was resolved.

huangapple
  • 本文由 发表于 2020年10月6日 17:00:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/64222533.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定