简体   繁体   English

构造函数参数的优化

[英]Optimization in constructor parameters

I'm setting parameter directly into DTO which output we are getting from HQL我将参数直接设置到 DTO 中,我们从 HQL 获得 output

Below is the HQL:以下是 HQL:

@Query(value = "SELECT new com.test.vos.CustomerDetails(firstname, lastName, address1, address2, address3, id, companyName, companyAddress, otherDetails) "
            + "FROM MstCustomer mc "
            + "INNER JOIN mc.mstAddress md "
            + "INNER JOIN mc.MstCompany mComapny "
            + "WHERE mc.mobileNo = :mobileNo ")
public List<CustomerDetails> getCustomerDetails(@Param("mobileNo") Integer mobileNo);

DTO: DTO:

public class CustomerDetails {
    private String firstName;
    private String lastName;
    private String address1;
    private String address2;
    private String address3;
    private String id;
    private String companyName;
    private String companyAddress;
    privatr String otherDetails;

    public CustomerDetails(String firstName, String lastName, String address1, String address2, String address3, String id, String companyName, String companyAddress, String otherDetails) {
        super();
        this.firstName = storeCode;
        this.lastName = lastName;
        this.address1 = address1;
        this.address2 = address2;
        this.address3 = address3;
        this.id = id;
        this.companyName = companyName;
        this.companyAddress = companyAddress;
        this.otherDetails = otherDetails;
    }

    // Getter and Setter
}

Above all code are working fine only issue is that its showing Constructor has 9 parameters, which is greater than 7 authorized.最重要的是,代码运行良好,唯一的问题是它显示的构造函数有 9 个参数,大于 7 个授权。

How to resolved that warning?如何解决该警告? What would be best approach?什么是最好的方法?

Use a Builder pattern to get one parameter (builder) in constructor使用Builder 模式在构造函数中获取一个参数(builder)

 private CustomerDetails(CustomerDetailsBuilder builder) {
    // ... set all fields using builder
 public static class CustomerDetailsBuilder
    //...update all parameters and build method

This uses a additional class UserBuilder which helps us in building desired User object with all mandatory attributes and combination of optional attributes, without loosing the immutability.这使用了一个额外的 class UserBuilder,它帮助我们构建所需的用户 object,其中包含所有必需属性和可选属性的组合,而不会失去不变性。

For example例如

CustomerDetails customerDetails = new CustomerDetails.CustomerDetailsBuilder("Lokesh", "Gupta")
.address1("street 1")
.address2("Floor 2")
.address3("Fake address 1234")
.build();

Another option is lombok's @AllArgsConstructor另一种选择是龙目岛的@AllArgsConstructor

Generates an all-args constructor.生成一个全参数构造函数。 An all-args constructor requires one argument for every field in the class.全参数构造函数需要 class 中的每个字段都有一个参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM