spring boot中的外键(mysql、hibernate、jpa)

kokeuurv  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(550)

我正在尝试使用springboot编写restfulapi,但我无法找到在数据库中Map关系的方法。我有一个用户和一个报表表。每个用户可以有多个报表,单个报表由“发件人”和“收件人”列组成,以指示谁向谁发送了报表。我的用户id是主键,对于报表表,我使用自动增量生成报表id作为主键。这是我的用户模型类-

@Entity
@Table (name = "user")
@EntityListeners(AuditingEntityListener.class)
public class User {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String firstName;

    private String lastName;

    private String email;

    private String password;

    @OneToMany(mappedBy = "user",cascade = CascadeType.ALL)
    private List<Report> reportReceivedList;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private List<Report> reportSentList;
    /* Getters and setters ..... */
}

这是我的报表模型类-

@Entity
@Table (name = "report")
@EntityListeners(AuditingEntityListener.class)
public class Report {
    @Id
    @Column (name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne()
    @JoinColumn(name = "from_user_id")
    private Long fromUserId;    //THIS SHOULD BE FROM "USER" TABLE

    @ManyToOne()
    @JoinColumn(referencedColumnName = "to_user_id")
    private Long toUserId;    //THIS SHOULD BE FROM "USER" TABLE

    @Temporal(TemporalType.DATE)
    @CreatedDate
    private Date createdAt;

    private String observation;

    private String context;

    //Other variables and getters and setters ..... 
}

有人能告诉我一个正确定义这种关系的方法吗。我现在的模型不行。另外,我希望在删除用户后立即删除报表类中的行。谢谢!

oprakyz7

oprakyz71#

我最后修改了我的用户类,如下所示-

@OneToMany(cascade = CascadeType.ALL, targetEntity = Report.class)
@JoinColumn(name = "to_user_id")
private List<Report> reportReceivedList;

@OneToMany(cascade = CascadeType.ALL, targetEntity = Report.class)
@JoinColumn(name = "from_user_id")
private List<Report> reportSentList;

把我的报告课改成-

@Column(name = "from_user_id")
private Long fromUserId;

@Column(name = "to_user_id")
private Long toUserId;

相关问题