使用Java JPA和Spring Data在MYSQL数据库中存储结构化注释

时间:2015-09-29 21:02:59

标签: spring hibernate jpa spring-data

使用Spring Data和Java JPA,我想在MYSQL表中存储注释线程。评论是关于一些数据的,每个评论都可以有任意数量的儿童评论(想想Reddit)。我想知道这个Java类是否有意义满足我的需求。

@Entity
public class Comment extends Identified {

    // Comment data
    @Column(nullable=false)
    private String data;

    // Parent comment
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(nullable=true)
    private Comment parent;

    // Sub comments
    @OneToMany(fetch=FetchType.EAGER)
    @JoinColumn(nullable=true, mappedBy="parent")
    private Set<Comment> children;

    public Comment() { }
    ....

为了澄清,我的主要关注点是将ManyToOne和OneToMany关系同时提供给同一个班级。这似乎很难看,但也是表达这种关系的唯一方式。

1 个答案:

答案 0 :(得分:2)

我向你保证你的绘图完全正常,我甚至会说平常。两个关系(多对一和一对多)在DB中使用不同的概念实现,不会发生冲突。由于关系是双向的,因此两个映射都代表两个不同链接的不同目的(一个是与父级的关系,另一个是与子级的关系)。

相关问题