【发布时间】:2020-04-08 04:41:44
【问题描述】:
Spring-boot中有这样一个项目:
模型页面:
@Entity
@Table(name = "pages")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Page implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "color")
private String color;
@OneToMany(mappedBy = "page", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Note> note;
// constructor, getters and setters
Model Note(一页可以有多个notes,notes.page_id是pages.id的外键):
@Entity
@Table(name = "notes")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Note implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "content")
private String content;
@Column(name = "title")
private String title;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "page_id")
private Page page;
// constructor, getters and setters
控制器:
public ResponseEntity<Object> createPage(@RequestBody Page page) {
pageRepository.saveAndFlush(page);
return new ResponseEntity("OK", HttpStatus.OK);
}
当我使用以下 Json 请求正文向端点发出 Post 请求时
{
"id": null,
"color": "yellow",
"note": [
{
"id": null,
"title": "Java",
"content": "Java is awesome",
"page": null
},
{
"id": null,
"title": "Python",
"content": "Python is good",
"page": null
}
]
}
新记录生成到数据库,页面id和note id生成正确,但是notes.page_id字段仍然为空。
表pages:
id|color |
1 |yellow |
表notes:
id| content |title |page_id|
1 | Java is awesome|Java | null |
2 | Python is good |Python| null |
问题是:如何为 notes.page_id 提供 pages 表的自动生成 ID?
【问题讨论】:
-
添加 PageRepository 的代码。另外,您是否尝试过在 @Embeddable 上做笔记?
标签: java spring-boot jpa repository