简体   繁体   中英

Spring Mapping using a custom mapper method

I have two objects with all the same members except for the date member. In Obj1.date is a java.sql.Date, and Obj2.date is a long (epoch).

I need to write a mapper to map obj1 to obj2. This is what I tried to do:

@Named("sqlDateToEpoch")
default long sqlDateToEpoch(Date timestamp) throws ParseException {
    return myUtils.sqlDateToEpoch(timestamp);
}

@Mapping(source = "date", target = "date", qualifiedByName = "sqlDateToEpoch")
Obj2 toObj2(Obj1 source);

List<Obj2> toRecordList(List<Obj1> source);

But the mapperImpl just has its own implementation for the date conversion:

if (source.getDate() != null) {
    Obj2.setDate(Long.parseLong(source.getDate()));
}

I'm getting:

java.lang.NumberFormatException: For input string: "2019-04-02 00:00:00.0"

What is the right way for this kind of conversion?

I think that the reason why it doesn't work is because your source.getDate() is returning a String and not a java.sql.Date . This leads to MapStruct using the implicit String to long conversion.

In order to fix this you would either need to make sure that source.getDate() returns java.sql.Date or add a method that would get a String and return Long .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM