Adding a calculated field on jpa + jackson

2019-09-06 00:27发布

问题:

How to add a calculated field to an entity?

DB table

table person {
    id number,
    first_name varchar,
    last_name varchar,
    ...
}

Java entity

public class person {
    BigDecimal id;
    String firstName;
    String lastName;
...//getters and setters

    //what to add here???
    public String getFullName() {
        return firstName + " " + lastname;
    }
}

I tried adding @Transient, but the field is ignored when converting to json. I tried just leaving the method there, throws an exception that the setter is missing. adding the setter throws another exception that the field does not exist in the DB. I tried adding @Transient and @JsonPropert, but the field is ignored when converting to json. I tried adding @Formula, but hibernate (i think) says it is not implemented.

The idea is to have a simple calculated field that is ignored by jpa/hibernate but is used by jackson. How can I accomplish this?

EDIT

Example full class

@Entity
@Table(name="FDF_PATIENT_COUNTIE")
@JsonIdentityInfo(generator = JSOGGenerator.class)
@JsonIgnoreProperties(ignoreUnknown = true)
@Audited
public class PatientCounty extends FgaBaseClass {

    private static final long serialVersionUID = 1425318521043179798L;

    private BigDecimal id;
    private County FCounties;
    private Patient patients;

    public PatientCounty() {
    }

    public PatientCounty(County FCounties, Patient patients) {
        this.FCounties = FCounties;
        this.patients = patients;
    }

    @SequenceGenerator(name="generator", sequenceName="FDF_PATIENT_COUNTIE_SEQ")
    @Id
    @GeneratedValue(strategy=SEQUENCE, generator="generator")
    @Column(name="ID", unique=true, nullable=false, precision=22, scale=0)
    public BigDecimal getId() {
        return this.id;
    }

    public void setId(BigDecimal id) {
        this.id = id;
    }

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="ID_F_COUNTIE")
    public County getFCounties() {
        return this.FCounties;
    }

    public void setFCounties(County FCounties) {
        this.FCounties = FCounties;
    }

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="ID_FDF_PATIENT")
    public Patient getPatients() {
        return this.patients;
    }

    public void setPatients(Patient patients) {
        this.patients = patients;
    }
}