I am currently working on a Java EE application and so I have multiple layers in my application server-side (succintly) :
My question is, since I always convert Entities to BO to prevent DB overwrites and reducing workload, is it good practice to include a constructor in BO that takes an Entity as parameters ?
See my code below :
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
}
Is it good practice ? Or should I put this method in a service class ? Thank you for your help.
In my opinion rather create Converter classes that will do the conversion to and from Entities and BO.
If you create BO constructor with Entity as parameter, In that way your BO will have dependency on Entities. Which is not a good practice. Because then the one who will be using BO will need to have to have definition of Entities also available with them.
And the first option with multiple parameter is also not a good practice. Keeping parameter less than 5 is considered good practice.
If you create a different converter class with two parameters Entity and BO, will make code more cleaner and readable. As well as, will reduce unwanted dependencies in code.