在序列化之前在实体中生成瞬态属性

时间:2016-11-03 10:53:45

标签: spring spring-boot

我有一个具有临时fullname属性的用户实体。应该通过传入用户实体的lastname和firstname属性来调用我的Util服务上的方法来生成此fullname属性(这些属性不是瞬态的,而是只写的)。如何在实体序列化并在我的响应中返回之前执行此操作?

1 个答案:

答案 0 :(得分:0)

您可以在模型中执行此操作。我创建简单的Person模型并执行此操作。

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;

@Entity
@Table(name = "PERSON")
public class Person implements Serializable {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "FIRSTNAME")
    private String firstName;

    @Column(name = "LASTNAME")
    private String lastName;

    @Transient
    private String fullName;

    public Long getId() {
        return id;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFullName() {
        fullName = firstName + " " + lastName;
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

}