Java 对象构造函数和良好实践

Java Object Constructors and Good Practices

我目前正在开发 Java EE 应用程序,因此我的应用程序服务器端有多个层(简洁):

我的问题是,由于我总是将 Entities 转换为 BO 以防止 DB 覆盖并减少工作量,因此在 BO 中包含一个以 Entity 作为参数的构造函数是否是一个好习惯?

请参阅下面的代码:

Livraison.java

package my.tree.model;

imports


@Entity
public class Livraison {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private LocalDate date;
    @ManyToOne
    @JoinColumn(name = "FournisseurId", nullable = false)
    private Fournisseur fournisseur;
    @ManyToOne
    @JoinColumn(name = "CategorieId", nullable = false)
    private Categorie categorie;
    private Integer netTotal;
    private String prefixCode;
    private Integer compte;
    @Transient
    private List<Palette> palettes = new ArrayList<>();

    public Livraison() {}

    public Integer getId() {
        return id;
    }
    
    //getters and setters
}

LivraisonBo.java

package my.tree.bo;

import Livraison;

public class LivraisonBo {
    private int id;
    private String date;
    private int fournisseurId;
    private int categorieId;
    private Integer netTotal;
    private String prefix;
    private Integer compte;


    public LivraisonBo() {
    }

    //classic constructor
    public LivraisonBo(int id, String date, int fournisseurId, int categorieId, Integer netTotal, String prefix, Integer compte) {
        this.id = id;
        this.date = date;
        this.fournisseurId = fournisseurId;
        this.categorieId = categorieId;
        this.netTotal = netTotal;
        this.prefix = prefix;
        this.compte = compte;
    }

    // constructor taking an entity as parameter
    public LivraisonBo(Livraison l) {
        this.id = l.getId();
        this.date = l.getDate().toString();
        this.fournisseurId = l.getFournisseur().getId();
        this.categorieId = l.getCategorie().getId();
        this.netTotal = l.getNetTotal();
        this.prefix = l.getPrefixCode();
        this.compte = l.getCompte();
    }
    
    //getters and setters
}

这是好的做法吗?或者我应该把这个方法放在服务 class 中吗? 谢谢你的帮助。

在我看来,宁可创建转换器 classes 来进行实体和 BO 之间的转换。

如果您使用实体作为参数创建 BO 构造函数,那么您的 BO 将依赖于实体。这不是一个好习惯。因为这样一来,将使用 BO 的人将需要拥有对实体也可用的定义。

而且第一个带有多个参数的选项也不是一个好的做法。保持参数小于 5 被认为是好的做法。

如果您使用两个参数 Entity 和 BO 创建不同的转换器 class,将使代码更清晰和可读。以及,将减少代码中不需要的依赖性。