Entity attribute based on a field from another table - Hibernate

Asked

Viewed 36 times

1

I have a microservice raised using Spring, Restful and Hibernate. I would like to know how I can modify an attribute of this json microservice, based on a condition, obtained through a query to the bank.

Below, a piece of the code of my Entity.

@Entity
@Table(name = "funcoes")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(allowGetters = true)
public class Funcoes {

@Id
@Column(name = "FUNCOD")
private String funcod;


@Column(name = "FUNFOR")
private String funfor;


@Column(name = "SISTEMA")
private String sistema;

}
}

I would like to compare the attribute sistema, if, based on a query, display a value x or a value y in my json.

1 answer

1

You need more flexibility to do what you want. And you’re having this problem by using the JPA entity as well to represent Json. In general, it is best to avoid mixing these two responsibilities.

What I point out to you is to create a new class that will be used only to represent the information in Json. We may call it FuncoesJson or FuncoesDto:

public class FuncoesDto {

    private String funcod;
    private String funfor;
    private String sistema;

    //gets e sets

}

To change what goes in the variable sistema, you can make this decision before you populate it with the entity information Funcoes. Take an example:

Funcoes funcoes = em.findOne(123L, Funcoes.class);

FuncoesDto dto = new FuncoesDto();
dto.setFuncod(funcoes.getFuncod());
dto.setFunfor(funcoes.getFunfor());

if (funcoes.getSistema().equals("valorConsulta")) {
    dto.setSistema("X");
} else {
    dto.setSistema("Y");
}

return dto;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.