8

I have the following abstract class:

public abstract class StandardTimeStamp {

  @Temporal(TemporalType.TIMESTAMP)
  @Column(nullable = false)
  @JsonIgnore
  private Date lastUpdated;

  @PreUpdate
  public void generatelastUpdated() {
    this.lastUpdated = new Date();
  }

  public Date getLastUpdated() {
    return lastUpdated;
  }

  public void setLastUpdated(Date lastUpdated) {
    this.lastUpdated = lastUpdated;
  }
}

I have an entity that is a subclass in which I need the lastUpdate value to be sent to the browser, so I need to override the @JsonIgnore. I have tried a few things, the following code being one of them:

public class MyEntity extends StandardTimestamp implements Serializable {

  @Column(name = "LastUpdated")
  private Date lastUpdated;

  @JsonIgnore(false)
  @Override
  public Date getLastUpdated() {
    return lastUpdated;
  }
}

This does add the lastUpdated attribute on the JSON response, however its value is null when it is not null in the database. I have other Dates in the subclass that work, but they aren't hidden with @IgnoreJson in the super class.

Any thoughts?

Nick Suwyn
  • 501
  • 1
  • 5
  • 21

1 Answers1

16

You're introducing a second field named lastUpdated with this declaration

@Column(name = "LastUpdated")
private Date lastUpdated;

in your subtype MyEntity. I'm not sure how the database mapper handles this, but it seems redundant to me.

I can see two options.

One, get rid of this new field and have your overriden getLastUpdated method delegate to its super implementation. For example

@Override
@JsonIgnore(false)
@JsonProperty
public Date getLastUpdated() {
    return super.getLastUpdated();
}

When serializing a MyEntity object, Jackson will discover a single property through this accessor, lastUpdated, and use it to generate the JSON. It'll end up retrieving it from the superclass.

Two, use the class annotation @JsonIgnoreProperties to mark the ignored properties in the superclass

@JsonIgnoreProperties("lastUpdated")
abstract class StandardTimeStamp {

then clear (or add different values to) that "list" in the subclass

@JsonIgnoreProperties()
class MyEntity extends StandardTimeStamp implements Serializable {

Jackson will only use the annotation on the subclass, if it's present, and ignore the annotation on the superclass.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • This works, however I am still getting null in the JSON attribute on the front-end, but I think that is on the database side. I will keep looking into that. Thanks for the great answer! :) – Nick Suwyn May 06 '16 at 15:42