【问题标题】:How to map with dozer a data type to different data type?如何使用推土机将数据类型映射到不同的数据类型?
【发布时间】:2017-04-19 14:35:36
【问题描述】:

我有一个 User 和 UserDTO 类,但在 dto 类中我不想使用 LocalDateTime,我想将其转换为长类型。 (因为 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..
}

您会看到实体 User 中的日期是 LocalDateTime,而 DTO 中的日期很长。我想用这个推土机:

    UserDTO destObject =
            mapper.map(user, UserDTO.class);

LocalDateTime 更改代码为 long:

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

映射器是否可能知道将 LocalDateTime 更改为 long?我可以以某种方式配置它吗?感谢您的帮助!

【问题讨论】:

    标签: java dozer


    【解决方案1】:

    最后我找到了一个解决方案,它是从 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>
    

    我认为它可以处理任何数据类型,只需要编写更多的转换器,或者智能地编写这个转换器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-08
      相关资源
      最近更新 更多