【BeanUtil工具类】BeanUtil.copyProperties,自动把user当中的属性拷贝到UserDTO对象中

自动把user当中的属性拷贝到UserDTO对象中

User

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("tb_user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 主键
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /**
     * 手机号码
     */
    private String phone;

    /**
     * 密码,加密存储
     */
    private String password;

    /**
     * 昵称,默认是随机字符
     */
    private String nickName;

    /**
     * 用户头像
     */
    private String icon = "";

    /**
     * 创建时间
     */
    private LocalDateTime createTime;

    /**
     * 更新时间
     */
    private LocalDateTime updateTime;
}

UserDTO

@Data
public class UserDTO {
    private Long id;
    private String nickName;
    private String icon;
}

BeanUtil

import cn.hutool.core.bean.BeanUtil;

// 只会将UserDTO中有的属性从User中拷贝过来
UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class); 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据提供的引用内容,可以得知BeanUtils.copyProperties()方法存在于两个不同的类,分别为org.springframework.beans.BeanUtils和org.apache.commons.beanutils.BeanUtils。这两个类的copyProperties()方法传递参数的赋值是相反的,即在org.springframework.beans.BeanUtilscopyProperties(A,B)的结果是将A拷贝到B;而在org.apache.commons.beanutils.BeanUtilscopyProperties(A,B)的结果是将B拷贝到A。 因此,如果需要使用BeanUtils.copyProperties()方法,需要先确定使用的是哪个类的方法,并根据需要传递正确的参数。 下面是两个类copyProperties()方法的使用示例: 1. org.springframework.beans.BeanUtilscopyProperties()方法,将A对象属性拷贝到B对象: ```python from myapp.models import A, B from django.shortcuts import get_object_or_404 from django.http import HttpResponse from org.springframework.beans import BeanUtils def my_view(request, pk): a = get_object_or_404(A, pk=pk) b = B() BeanUtils.copyProperties(a, b) b.save() return HttpResponse('Copy successful!') ``` 2. org.apache.commons.beanutils.BeanUtilscopyProperties()方法,将B对象属性拷贝到A对象: ```python from myapp.models import A, B from django.shortcuts import get_object_or_404 from django.http import HttpResponse from org.apache.commons.beanutils import BeanUtils def my_view(request, pk): a = A() b = get_object_or_404(B, pk=pk) BeanUtils.copyProperties(a, b) a.save() return HttpResponse('Copy successful!') ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值