当 pojo 层的实例属性过多时,一个个手写 setter()
或 getter()
代码过于冗余,可以用 Spring 自带的工具类 BeanUtils
解决这一问题:
// pojo层:
@Data
public class Commodity {
@TableId(type = IdType.AUTO)
private Integer id;
private Integer number;
private String comName;
private String comBrand;
private Integer price;
private String photo;
private Integer inventory;
private String status;
private Integer sale;
private String description;
}
// 这里将参数除了自增唯一的id以外全部封装到 ProductParm 类中
@Data
public class ProductParam {
private Integer number;
private String comName;
private String comBrand;
private Integer price;
private String photo;
private Integer inventory;
private String status;
private Integer sale;
private String description;
}
Service 的实现类中:
Commodity commodity = new Commodity();
BeanUtils.copyProperties(productParam, commodity); // 参数1为来源,参数2为目标
commodityMapper.insert(commodity);
另外,最好保证属性名一致,不一致的情况尚未验证。