ModelMapper - 将 Collection<Object> 中的 Date 转换为 String (java)

ModelMapper - convert a Date inside a Collection<Object> to String (java)

我在这个论坛和其他网站上搜索了很多,但我的问题仍然存在。

我实际上是在使用 modelmapper 将实体转换为 DTO。

这是实体:

@Entity

public class Candidate implements Serializable {

@Id
@GeneratedValue (strategy=GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@Column (name = "name")
private String lastname;

@Column (name = "firstname")
private String firstname;

@Column (name = "phone")
private String phoneNumber;

@Column (name = "mail")
private String email;

@Column (name = "title")
private int title;

@OneToMany (mappedBy = "candidateId")
private Collection<Candidature> Interviews;

这是候选实体(您在第一个实体集合中找到的实体):

public class Candidature implements Serializable {

@Id
@NotBlank
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private Long id;

@ManyToOne (fetch = FetchType.LAZY)
@JoinColumn (name = "candidat_id")
private Candidate candidateId;

@Column(name = "interview")
@Temporal (TemporalType.DATE)
private Date dateInterview;

@Column(name ="status")
private String status;

这是 DTO :

public class CandidateDTO {

private Long id;
private String lastname;
private String firstname;
private String phoneNumber;
private String email;
private String title;
private String dateLastInterview;

如您所见,存在一些差异。 我面临的问题是 DTO (dateLastInterview) 的最后一个属性来自 Collection<Candidature> 更准确地说它必须是最后一个 dateInterview 转换为 String.

将日期转换为字符串不是问题。既没有获取集合的最后一项。

但我无法让它与 modelMapper 一起工作。 这是我试过的示例代码:

modelMapper = new ModelMapper();
             Converter<Candidate, CandidateDTO> converter = new Converter<Candidate, CandidateDTO>()
             {
                 @Override
                 public CandidateDTO convert(MappingContext<Candidate, CandidateDTO> mappingContext) {

                     Candidate candidate = mappingContext.getSource();
                     CandidateDTO cdto = new CandidateDTO();

                     List<Candidature> list = (List) candidate.getInterviews();
                     Date date = list.get(list.size()-1).getDateInterview();

                     DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                     String dateInterviewConverted = df.format(date);

                     mappingContext.getDestination().setTitle(mappingContext.getSource().getTitle());
                     mappingContext.getDestination().setDateLastInterview(dateInterviewConverted);


                     return cdto;
                 }
             };

                modelMapper.createTypeMap(Candidate.class, CandidateDTO.class).setConverter(converter);

(我试过了,而不是上面的最后一行:modelMapper.addConverter(converter); 但结果相同)

但是它不起作用,我得到的所有属性都是空的。

我之前成功使用 map().setTitle(source.getTitle()); map().setDateLastInterview(dateInterviewConverted); 然后在我的 DTO "set" 方法中将 Date 转换为 String,但它似乎不应该在这里,而是进入 ModelMapper class 或正在使用它的 class。

你有想法吗?我是 modelMapper 的新手,我一直在浏览 google,但找不到(或者可能理解?)任何可能对我有帮助的回复。

谢谢

好的,我想我成功了。 使用转换器是正确的,但我没有正确使用它。对于转换器,您放在 <> 中的两个对象是转换器所关注的属性。

例如,对于第一个转换器,我想将Collection(来自对象Candidate)的转换参数化为String(以匹配DTO的属性)。

那么你只需要用 Class 和 ClassDTO 创建一个 PropertyMap,并且在 configure() 方法中你只需要提到将使用特殊参数的属性(其他的是正确的,因为它们尊重标准映射)。

Converter<Collection<Candidature>, String> convertLastDateToString = new Converter<Collection<Candidature>, String>() {
        public String convert(MappingContext<Collection<Candidature>, String> context) {

            List<Candidature> candidatureList = (List)context.getSource();

            String dateInterviewConverted = "";

            if (candidatureList.size() > 0) {
                Date lastInterview = candidatureList.get(0).getDateInterview();
                for (int i = 0; i < candidatureList.size(); i++) {
                    if (candidatureList.get(i).getDateInterview().after(lastInterview)) {
                        lastInterview = candidatureList.get(i).getDateInterview();
                    }
                }

                // converts the Date to String
                DateFormat df = new SimpleDateFormat(DATE_FORMAT);
                dateInterviewConverted = df.format(lastInterview);
            }

            return dateInterviewConverted;
        }
    };

    // allows custom conversion for Title attribute
    // the source (Candidate) has a title attribute in int type
    // the destination (CandidateDTO) has a title attributes in String type
    Converter<Integer, String> convertTitleToString = new Converter<Integer, String>(){
        public String convert(MappingContext<Integer, String> context){
           return Title.values()[context.getSource()].toString();
        }

    };

    // define explicit mappings between source and destination properties
    // does only concernes the attributes that will need custom mapping
    PropertyMap<Candidate, CandidateDTO> candidateMapping = new PropertyMap<Candidate, CandidateDTO>()
    {
        protected void configure()
        {
            // to map these two attributes, they will use the corresponding converters
            using(convertTitleToString).map(source.getTitle()).setTitle(null);
            using(convertLastDateToString).map(source.getCandidatures()).setDateLastInterview(null);
        }
    };

    // add the mapping settings to the ModelMapper
    modelMapper.addMappings(candidateMapping);