转换为JSON时缺少JPA列

时间:2017-09-21 12:44:01

标签: spring-data-jpa spring-websocket

我在'counter'实体中有一个'created'列。此列应该是自动生成的时间戳,因此我使计数器类看起来像这样:

@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;
    }
}

登录后端显示此“已创建”列正确无误:

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)

但是当通过REST websocket将此对象发送到前端时,创建的列将丢失:

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

有人能告诉我问题出在哪里吗?感谢。

1 个答案:

答案 0 :(得分:0)

好的,解决方案应该是这样的:

@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();
}

我没有发现任何解决方案可以填充对象,数据库和JSON。任何帮助表示赞赏。