Search code examples
spring-data-jpaspring-websocket

JPA column missing when converting to JSON


I have a 'created' column inside a 'counter' entity. This column should be an auto-generated timestamp thus I made the counter class looks like this:

@Data
@Entity
@Table(name = "counter")
public class Counter {
    private static final Logger logger = LoggerFactory.getLogger(Counter.class);

    @Id
    @SequenceGenerator(name="counter_seq_id", sequenceName="counter_seq_id", allocationSize = 1, initialValue = 1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="counter_seq_id")
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;

    @Getter
    @Column(name = "sensor_id", updatable = false, nullable = false)
    private String sensorId;

    @Getter
    @Column(name = "customer_number", updatable = false, nullable = false)
    private int customerNumber;

    @Getter
    @CreationTimestamp
    @Column(name = "created", updatable = false, insertable = false)
    private Timestamp created;

    /**
     * Private constructor.
     */
    private Counter() {}

    /**
     * Public constructor.
     *
     * @param sensorId Sensor ID.
     * @param customerNumber Number of customers in shop.
     */
    public Counter(String sensorId, int customerNumber) {
        logger.debug("Counter constructor sensorId={}, number={}", sensorId, customerNumber);

        this.sensorId = sensorId;
        this.customerNumber = customerNumber;
    }
}

Logs in backend shows this 'created' column is correct:

Counter constructor sensorId=S12345, number=20
newCounter counter=Counter(id=4, sensorId=S12345, customerNumber=20, created=2017-09-21 20:22:40.538)
getPath counter=Counter(id=4, sensorId=S12345, customerNumber=20, created=2017-09-21 20:22:40.538)

But when this object is sent to frontend via REST websocket, the created column is missing:

responseJson = {"sensorId":"S12345","customerNumber":20,"created":null,"_links":{"self":{"href":"http://localhost:8080/api/counters/4"},"counter":{"href":"http://localhost:8080/api/counters/4"}}}

Can anybody tell me where the problem is? Thanks.


Solution

  • Ok, solution should be like this:

    @Getter
    @Column(name = "created", updatable = false, nullable = false)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    private LocalDateTime created;
    
    /**
     * Public constructor.
     *
     * @param sensorId Sensor ID.
     * @param customerNumber Number of customers in shop.
     */
    public Counter(String sensorId, int customerNumber) {
        logger.debug("Counter constructor sensorId={}, number={}", sensorId, customerNumber);
    
        this.sensorId = sensorId;
        this.customerNumber = customerNumber;
        this.created = LocalDateTime.now();
    }