I have the following table defined with JPA:
@Data
@Entity
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(unique = true)
private String name;
private Integer budget;
private String description;
private Boolean isArchived;
private LocalDate archivedDate;
@Transient
private Integer usedBudget;
@NotNull
@ManyToOne
private Customer customer;
}
I have a REST-API-method getProjects()
which returns all projects from the database. usedBudged
is not persisted in the database and has to be calculated. In most cases when i call getProjects()
i do not need the usedBudget
attribute. But in one case i would like to calculate the usedBudget
of the project and send it directly with the project object, so i do not have to get all projects first and do a seperate API call for each project to get the usedBudget
. So in order to achieve that i added a usedBudget
property to the Project entity and marked it as transient. That way it does not get persisted in the database and whenever i want to get the usedBudget
, i just calculate it and set it before returning the project object. The only problem is that even if its not set(null) its getting send via JSON. Is there a way to ignore/not send this transient value whenever its set to null?
Another solution to my problem could be a helper class which extends Project and has that one additional attribute usedBudget
. So whenever i need the usedBudget
i would return the helper class and whenever i do not i just return the normal project(no transient usedBudget property in this case). That way i would never send useless null values.
Which of the approaches is better and is there maybe a better one?