简体   繁体   中英

Calculated Column In Hibernate In same Entity

I have as entity class Student in that I have roll_no , student_name , marks columns My Entity Class below:

    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;


    @Entity
    @Table(name = "student")
    public class Student{

    @Id 
    private int roll_no;
    private String student_name;
    private int marks; 

    public int getRoll_no() {
            return roll_no;
        }

        public void setRoll_no(int levelid) {
            this.roll_no = roll_no;
        }

public String getStudent_name() {
        return student_name;
    }

    public void setStudent_name(String student_name) {
        this.student_name = student_name;
    }


public int getMarks() {
        return marks;
    }

    public void setMarks(int marks) {
        this.marks= marks;
    }

    }

I want to execute A NamedQuery Like :

select *, (case when marks > 35  then 'Pass' else 'Fail' end)  as final_result from student

How can I add calculated new column final_result in my entity class. I don't want to add it in my actual table in DB Thanks

You don't need to bother the DB, make a getter:

public String getFinalResult() {
    return this.marks > 35 ? "Pass" : "Fail";
}

EDIT:

If you need finalResult to be an field for the json parser than try the following:

@Transient
@JsonProperty(access = Access.READ_ONLY)
private String finalResult;

private int marks;

public void setMarks(int marks) {
    this.marks = marks;
    setFinalResult();
}

private String getFinalResult() {
    return this.finalResult;
}

@PostLoad
private void setFinalResult() {
    this.finalResult = this.marks > 35 ? "Pass" : "Fail";
}

The @Transient annotation prevent the field from persisting and @PostLoad ensures the field is set after the Entity is loaded from jpa.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM