ModelMapper mapping enum to same enum returns null

2.9k Views Asked by At

I have an entity, with an enum type field and a DTO with the same enum type and field name.

@Entity
@Table(name = "user")
public class UserModel {

    @Id
    @GeneratedValue
    private int id;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    private Gender gender;

    // getters and setters
}

public class UserDto {
    public Gender gender;
}

public enum Gender {
    male,
    female,
    unisex
}

I'm using modelMapper by creating a new object with no additional config.

But after mapping the dto to entity object, gender is null on the entity object.

Dto object has gender, I've checked that much.

UserModel user = mapper.map(dto, UserModel.class);
user.getGender(); // null

Please help me understand the issue.

1

There are 1 best solutions below

0
pirho On

Your UserDTO.gender is a public field without a getter. On the other hand UserModel.gender is a private field with getter.

ModelMapper seems not to mix field and method accesses so you need to access both sides either by filed or method.

Try to configure your ModelMapper to read/write private fields so not using getters & setters:

ModelMapper mm = new ModelMapper();
mm.getConfiguration()
    .setFieldMatchingEnabled(true)
    .setFieldAccessLevel(AccessLevel.PRIVATE);

Another option would be to declare your UserDto.gender private and have a getter for that.