I have the following problem, I am trying to create a method that converts DTO's to Entity's and vice versa until the moment I arrived at the following method that converts perfectly when they are compatible attributes String to String , Long to Long , and so on. Of course the premise is that the types I want to convert are always the same.
public static <T> void ConvertDtoToEntity(T dto, T entity){
Field[] entitycampos = entity.getClass().getDeclaredFields();
Field[] dtocampos = dto.getClass().getDeclaredFields();
for (Field entityfield : entitycampos) {
entityfield.setAccessible(true);
for (Field dtofield : dtocampos) {
dtofield.setAccessible(true);
if(!entityfield.getName().equals("serialVersionUID")
&& entityfield.getName().equals(dtofield.getName()))
{
try {
entityfield.set(entity, dtofield.get(dto));
break;
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
Only the problem is when converting List, Set and or other dts or other entities that are within that dto. EX DTO that convert perfectly to an entity:
public class CupomHistoricoDto implements Serializable{
private static final long serialVersionUID = 1L;
private BigDecimal seqcupomhistorico;
private int quantidade;
private Date data;
private long nroempresa;
EX Entity that convert perfectly to a dto:
public class CupomHistoricoEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
@Column(name = "SEQCUPOMHISTORICO", unique = true, nullable = false)
private BigDecimal seqcupomhistorico;
@Column(name = "QUANTIDADE", nullable = false)
private int quantidade;
@Column(name = "DATA", nullable = false)
private Date data;
@Column(name = "NROEMPRESA", nullable = false)
private long nroempresa;
EX DTO that is not converting to an entity
public class CupomHistoricoDto implements Serializable{
private static final long serialVersionUID = 1L;
private BigDecimal seqcupomhistorico;
private int quantidade;
private Date data;
private long nroempresa;
private CupomHistoricoDetalheDto detalhe;
EX Entity
public class CupomHistoricoEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
@Column(name = "SEQCUPOMHISTORICO", unique = true, nullable = false)
private BigDecimal seqcupomhistorico;
@Column(name = "QUANTIDADE", nullable = false)
private int quantidade;
@Column(name = "DATA", nullable = false)
private Date data;
@Column(name = "NROEMPRESA", nullable = false)
private long nroempresa;
@OneToOne
@JoinColumn(name = "seqdetalhe", referencedColumnName = "SEQDETALHE")
private CupomHistoricoDetalheEntity detalhe;
Someone would have some idea how to implement this method or have already done something similar.
NOTE: I am testing if I can do what I want using Apache's BeanUtils.