Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/391.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用推土机将数据类型映射到不同的数据类型?_Java_Dozer - Fatal编程技术网

Java 如何使用推土机将数据类型映射到不同的数据类型?

Java 如何使用推土机将数据类型映射到不同的数据类型?,java,dozer,Java,Dozer,我有一个User和UserDTO类,但在dto类中我不想使用LocalDateTime,我想将其转换为long类型。(因为protobuf不支持日期)。因此,在代码中: 我的用户实体类: public class User { private String name,password; private LocalDateTime date; //getters-setters, tostring.. } 我的DTO: public class UserDTO { pri

我有一个User和UserDTO类,但在dto类中我不想使用LocalDateTime,我想将其转换为long类型。(因为protobuf不支持日期)。因此,在代码中:

我的用户实体类:

public class User {
    private String name,password;
    private LocalDateTime date;
//getters-setters, tostring..
}
我的DTO:

public class UserDTO {
    private String name,password;
    private long date;
//getters-setters, tostring..
}
您可以看到实体用户中的日期是LocalDateTime,而DTO中的日期很长。我想使用这个dozermapper:

    UserDTO destObject =
            mapper.map(user, UserDTO.class);
LocalDateTime将代码更改为长代码:

private static long setDateToLong(LocalDateTime date) {        
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    String dateString = date.format(formatter);
    return Long.parseLong(dateString);        
}

映射程序是否可能知道将LocalDateTime更改为long?我可以配置它吗?谢谢你的帮助

最后我找到了一个解决方案,它是从LocalDateTime到String,再从String到LocalDateTime创建的。我必须创建一个转换器:

public class DozerConverter implements CustomConverter {
    @Override
    public Object convert(Object destination, Object source, Class destClass, Class sourceClass) {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        if(source instanceof String) {
            String sourceTime = (String) source;
            return LocalDateTime.parse(sourceTime, formatter);
        } else if (source instanceof LocalDateTime) {
            LocalDateTime sourceTime = (LocalDateTime) source;
            return sourceTime.toString();
        }
        return null;
    }
}

在自定义xml中,我必须添加如下自定义转换器属性:

<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://dozer.sourceforge.net
      http://dozer.sourceforge.net/schema/beanmapping.xsd">
    <mapping>
        <class-a>mypackage.UserDTO</class-a>
        <class-b>mypackage.User</class-b>
        <field custom-converter="mypackage.DozerConverter">
            <a>lastLoggedInTime</a>
            <b>lastLoggedInTime</b>
        </field>
    </mapping>
</mappings>

mypackage.UserDTO
mypackage.User
最后记录时间
最后记录时间
我认为它可以与任何数据类型一起工作,只需编写更多的转换器,或者智能地编写此转换器