【问题标题】:java: how to duplicate value with different parameter typejava:如何使用不同的参数类型复制值
【发布时间】:2018-11-14 07:56:05
【问题描述】:

我的 spring 代码有问题,我正在努力寻找解决方案。

我想用不同的参数类型将我的值从 dto 解析到模型,反之亦然。

以下是 SC: 用户模型:

public Class UserModel {
private int userId;
private Date dob;
//setter getter
}

UserDto:

public Class UserDto {
private String userId;
private String dob;
//setter getter
}

我尝试了很多方法,例如使用ObjectMapper和PropertyUtilsBean,但总是显示错误。

你们谁有最好的解决方案?请帮忙

【问题讨论】:

  • 首先,date 应该是 Date。另外,您需要告诉我们您遇到了什么错误。
  • 好的,谢谢...我将编辑问题...如果使用 PropertyUtilsBean:java.lang.IllegalArgumentException:未指定目标 bean...如果使用 ObjectMapper:org.hibernate.TypeMismatchException:提供的 id com.mycore.thebe.entity.User 类的类型错误。预期:类 java.lang.Integer,得到类 java.lang.String

标签: java spring model dto


【解决方案1】:

这个解决方案对我有用:

import org.apache.commons.beanutils.*;
import org.apache.commons.beanutils.converters.DateConverter;

import java.util.Date;

public class Main {

    public static void main(String[] args) throws Exception {
        DateConverter converter = new DateConverter();
        converter.setPattern("yyyy-MM-dd");

        ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean();
        convertUtilsBean.register(converter, Date.class);

        BeanUtilsBean beanUtilsBean = new BeanUtilsBean(convertUtilsBean, new PropertyUtilsBean());

        UserDto dto = new UserDto("42", "2018-11-14");
        System.out.println("dto.getUserId() = " + dto.getUserId());
        System.out.println("dto.getDob() = " + dto.getDob());

        UserModel model = new UserModel();
        beanUtilsBean.copyProperties(model, dto);

        System.out.println("model.getUserId() = " + model.getUserId());
        System.out.println("model.getDob() = " + model.getDob());
    }

}

您可以找到完整的示例源代码here

【讨论】:

  • 我试过了,但它有错误.....线程“main” java.lang.NoSuchMethodError: org.slf4j.spi.LocationAwareLogger.log 中的异常
  • 我可以使用 mvn exec:java -Dexec.mainClass=sk.ygor.stackoverflow.q53295382.Main 从 IntelliJ 和 Maven 执行我的示例。我相信,您的例外与PropertyUtilsBean 无关。请发送整个堆栈跟踪。
猜你喜欢
  • 2022-11-14
  • 2013-11-21
  • 2018-08-26
  • 1970-01-01
  • 1970-01-01
  • 2017-09-18
  • 2020-12-23
  • 2013-12-25
  • 1970-01-01
相关资源
最近更新 更多