【问题标题】:JPA serializing/deserializing nested autogenerated fieldsJPA 序列化/反序列化嵌套的自动生成字段
【发布时间】: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


【解决方案1】:

如下修改你的笔记类代码

@ManyToOne
@JoinColumn(name="page_id", nullable=false)
private Page page;

【讨论】:

    【解决方案2】:

    JPA 实体的原理其实很简单。

    您的 JPA 实体中有一个字段,该字段映射到数据库表中的列。

    此字段包含的内容将写入表中相应的数据库列。

    您的Node.page 字段是映射到note.page_id 列的字段。 该字段的值为null。所以写入数据库列的是null

    如果你想在列中有一个页面ID,那么你需要在这个字段中有一个非空的page。所以你的代码需要做

    page.getNotes().forEach(note -> note.setPage(page))
    

    就这么简单和合乎逻辑。

    【讨论】:

      猜你喜欢
      • 2016-02-13
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      相关资源
      最近更新 更多