Can Spring JPA Entity Class Contain Non-DB Fields that Are not In a DB Table

jlp :

I am using Spring JPA and Spring Data Rest with SpringBoot. I have a DB table called user and an entity for this table. I have no controller for this application.

@Entity
@Table(name = "USER")
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "USER_ID")
    private Integer userid;

    @Basic(optional = false)
    @Column(name = "USER_NAME")
    private String username;
} 

And now, I need to add one more field which isn't a column in the USER table. It will be used by some monitoring tool for tracing purpose.

@Entity
@Table(name = "USER")
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "USER_ID")
    private Integer userid;

    @Basic(optional = false)
    @Column(name = "USER_NAME")
    private String username;

    private String tracer;  // this field is not in DB
} 

I am getting a jdbc.spi.SqlExceptionHelper - Invalid column name "tracer" after adding this field, which makes sense because this class is annotated as an entity. My question is that: is there a way to add a non-db field into an entity class? I guess not, but would like to know in case someone has a solution. Thanks.

Fabiano Oliveira :

Yes, just add the annotation @Transient to your field.

You can read more from the API docs:

https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/Transient.html

And here (section 37.1.2.1):

https://docs.oracle.com/javaee/7/tutorial/persistence-intro001.htm#BNBQA

Hope it helps.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=329772&siteId=1