title: Foreign Keys in Spring Boot (MySQL, Hibernate, JPA)
body: <p>I am trying to write a RESTful API using Spring Boot and I am not able to figure out a way to map my relations in the database. I have a User and a Reports table. Each User can have multiple Reports, and a single report consists of "FROM USER" and "TO USER" columns to indicate who sent the report and to whom. My User ID is the primary key and for the Report table, I am generating REPORT ID as the primary key using AUTO INCREMENT. Here is my User model class - </p>
  
  <pre><code>@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&lt;Report&gt; reportReceivedList;
  
      @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
      private List&lt;Report&gt; reportSentList;
      /* Getters and setters ..... */
  }
  </code></pre>
  
  <p>Here is my Report Model class - </p>
  
  <pre><code>@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 ..... 
  }
  </code></pre>
  
  <p>Can someone please show me a way to correctly define this relationship. My current model doesn't work. Also, I want rows from REPORT class to be deleted as soon as a user is deleted. Thanks!</p>