Search code examples
springspring-bootspring-data-rest

How to POST a new record which is referenced to another table


Trying to use Spring Data Rest:

I have 2 entities, with @ManyToOne relation:

@Data
@Entity
@NoArgsConstructor
@Table(name = "tasks")
public class Task {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, length = 150)
    private String title;

    @Lob
    private String description;

}
@Data
@Entity
@NoArgsConstructor
@Table(name = "comments")
public class Comment {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "task_id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    private Task task;

    @Lob
    @Column(nullable = false)
    private String comment;
}

I cannot add new comment which should be associated to 1 Task

POST http://localhost:9000/api/comments
Content-Type: application/json

{
  "comment": "Some text",
  "task_id": 1
}

This request returns:

POST http://localhost:9000/api/comments

HTTP/1.1 409 
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Content-Type: application/json
Transfer-Encoding: chunked
Date: Wed, 01 Jul 2020 16:36:25 GMT
Keep-Alive: timeout=60
Connection: keep-alive

{
  "cause": {
    "cause": {
      "cause": null,
      "message": "Column 'task_id' cannot be null"
    },
    "message": "could not execute statement"
  },
  "message": "could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement"
}
  1. First I created Task
  2. Tried to add comment to the task

If I get Task by id:

GET http://localhost:9000/api/tasks/1
Accept: application/json

It will return it:

{
  "title": "new task",
  "description": "more content",
  "priority": "HIGH",
  "todoDate": "2020-07-02 10:50",
  "_links": {
    "self": {
      "href": "http://localhost:9000/api/tasks/1"
    },
    "task": {
      "href": "http://localhost:9000/api/tasks/1"
    }
  }
}

What am I doing wrong ? Should I use bi-directional approach and add @OneToMany to Task entity or it's configurable somehow ?


Solution

  • Remove @JsonIgnore from task

    public class Comment {
    
        @ManyToOne(fetch = FetchType.LAZY, optional = false)
        @JoinColumn(name = "task_id", nullable = false)
        @OnDelete(action = OnDeleteAction.CASCADE)
        // @JsonIgnore
        private Task task;
    }
    

    and POST this:

    {
      "comment": "Some text",
      "task": "http://localhost:9000/api/tasks/1"
    }