1

我正在使用带有 Java 11 的 Spring Boot 2。我创建了以下 JPA 实体...

@Entity
@Table(name = "Mailings")
public class Mailing {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID id;
    
    @ManyToOne
    @NotNull
    private Card card;
    
    private String message;
    
    @Column(columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
    private java.sql.Timestamp mailingDate;
    
    @OneToOne(cascade = CascadeType.ALL)
    @NotNull
    private Address senderAddress;
    
    @OneToOne(cascade = CascadeType.ALL)
    @NotNull
    private Address recipientAddress;
}

当我启动我的开发应用程序时,这是在我的 PostGres 10 数据库中正确创建的......

cardmania=# \d mailings;
                      Table "public.mailings"
        Column        |            Type             |   Modifiers   
----------------------+-----------------------------+---------------
 id                   | uuid                        | not null
 creation_date        | timestamp without time zone | default now()
 message              | character varying(255)      | 
 card_id              | uuid                        | not null
 recipient_address_id | uuid                        | not null
 sender_address_id    | uuid                        | not null
Indexes:
    "mailings_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "fk5hy4mbv0ewd82t5b8b7shaxkc" FOREIGN KEY (sender_address_id) REFERENCES addresses(id)
    "fk67j1xe6kw5510en1daylstnnn" FOREIGN KEY (card_id) REFERENCES cards(id)
    "fknwiu32uusnxegnulcj1di158k" FOREIGN KEY (recipient_address_id) REFERENCES addresses(id)

然后我创建了这个控制器来处理 POST 请求......

@RestController
@RequestMapping("/api/mailing")
public class MailingController {

    @Autowired
    private MailingService mailingService;
    
    @PostMapping
    @ResponseStatus(code = HttpStatus.CREATED)
    public void create(@Valid @RequestBody Mailing mailing) {
        mailingService.save(mailing);
    }
    
}

但是我面临的一个问题是,当我使用 JSON 提交 POST 请求时,如下所示

{
  "senderAddress": {
    "name": "Joe Recipient",
    "city": "Los Angeles",
    "state": "California",
    "zip_code": "60615",
    "street": "555 Hello Way"
  },
  "recipientAddress": {
    "name": "Joe Recipient",
    "city": "Los Angeles",
    "state": "California",
    "zip_code": "60615",
    "street": "555 Hello Way"
  },
  "card": {
    "id": "05b7af7c-1de5-4a72-aebf-4c9e4d9acec3"
  },
  "message": "Hi"
}

该实体在我的数据库中正确创建,但“creation_date”字段为空,而不是使用当前时间戳填充。请注意,该列是使用“default now()”修饰符生成的,那么我还需要做什么才能正确填充我的时间戳列?

4

1 回答 1

0

如果只想用它的创建时间戳填充一列,您还可以使用@CreationTimestamp:

@CreationTimestamp
private Date mailingDate;
于 2020-06-24T16:51:42.220 回答