Sandeep Barnabas
Sandeep Barnabas

Reputation: 63

How do you set an attribute to the current OffsetDateTime (now) using MapStruct?

I’m trying to use MapStruct to map attributes on a class and among those attributes is a OffetDateTime variable that I need to set to the current time. However, when the MapperImpl class is generated, it cannot recognize the OffsetDateTime and ZoneOffset classes. So, for e.g.

public class MapThisClass {
    private OffsetDateTime time;

    // other attributes
}

I’m trying to set (in the mapping, the time to the current OffsetTime like below:

public class MapThisClassMapper {

    //. Map other attributes

    Mapping(target = “time”, expression = "java(OffsetDateTime.now(ZoneOffset.UTC))")
    public abstract MapThisClass cloneMapThisClass(MapThisClass mapThisObject, Clazz someOtherClassToMapFrom);
    

}

When I try to build, I get the following error.

ERROR] MapThisMapperImpl.java:[233,61] cannot find symbol
[ERROR]   symbol:   variable ZoneOffset
[ERROR]   location: class MapThisMapperImpl
[ERROR] MapThisMapperImpl.java:[233,42] cannot find symbol
[ERROR]   symbol:   variable OffsetDateTime
[ERROR]   location: class MapThisMapperImpl

I’m new to MapStruct. Is there a way for me to ensure that the MapperImpl class recognizes (automatically imports) the OffsetDateTime and ZoneOffset classes? Or maybe there is another way to do this and I need to go about this some other way?

Any insights/help would be greatly appreciated.

thanks!

Upvotes: 0

Views: 46

Answers (1)

June
June

Reputation: 385

Just add the imports to the interface or give the fully-qualified name in the expression:

@Mapper(imports = {OffsetDateTime.class, ZoneOffset.class})
public class MapThisClassMapper {

    //. Map other attributes

    Mapping(target = “time”, expression = "java(OffsetDateTime.now(ZoneOffset.UTC))")
    public abstract MapThisClass cloneMapThisClass(MapThisClass mapThisObject, Clazz someOtherClassToMapFrom);
    

}

or

public class MapThisClassMapper {

    //. Map other attributes

    Mapping(target = “time”, expression = "java(java.time.OffsetDateTime.now(java.time.ZoneOffset.UTC))")
    public abstract MapThisClass cloneMapThisClass(MapThisClass mapThisObject, Clazz someOtherClassToMapFrom);
    

}

Upvotes: 1

Related Questions