嵌套一对多关系JPA Spring Boot

时间:2018-08-17 01:56:21

标签: mysql spring-boot jpa

我有三个班级-文档,页面,句子。一个文档将具有多个页面,每个页面将具有多个句子。我正在尝试使用Spring Data JPA注释映射一对多关系。但是它仅在只有一层(如“文档”>“页面”)时有效。当它是Document> Page> Sentence时不起作用。

任何人都可以给我一个解决方案,以解决嵌套的一对多关系吗?

下面是我的课程。

@Entity
@Table(name = "PAGE")
public class Page implements Serializable {

    @Id
    @Column(name = "PAGE_ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long idPage;

    @Column(name = "PAGE_NUMBER")
    private int pageNum;

    @Lob
    @Column(name = "CONTENT")
    private String content;

    @ManyToMany(cascade = CascadeType.ALL)
    @Column(name = "SENTENCES")
    private List<Sentence> sentences = new ArrayList<>();

    // Setter Getters

}

@Entity
@Table(name = "SENTENCE")
public class Sentence implements Serializable {

    //private long idFile;

    //private long idPage;

    @Id
    @Column(name = "SENTENCE_ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name = "PAGE_NUMBER")
    private int pageNumber;

    @Column(name = "ORDER")
    private int ord;

    @Column(name = "CONTENT")
    private String content;

    @Column(name = "HASH")
    private String hash;

   // Setter Getters

}

targetSdkVersion

1 个答案:

答案 0 :(得分:0)

您的OneToMany映射不正确。对其进行如下纠正

@Entity
@Table(name = "DOCUMENT")
public class Document implements Serializable {
    ......

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "DOCUMENT_ID")  //Name the foreign key column in PAGE table to DOCUMENT_ID
    private List<Page> pages = new ArrayList<>();    
}

@Entity
@Table(name = "PAGE")
public class Page implements Serializable {
    ....

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "PAGE_ID") //Name the forein key column in PAGE table to PAGE_ID
    private List<Sentence> sentences = new ArrayList<>();
}

使用@JoinColumn注释而不是@Column来给出在数据库中的表之间进行物理映射的外键的名称。