javahibernatejpapost

How put the json data to foreign key of a table?


I have two entities.

Task

public class Task {

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

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

    @Column(name = "title")
    private String tilte;

    @JsonIgnore
    @ManyToOne
    @JoinColumn(name="project_id")
    private Project project;

    @ManyToOne
    @JoinColumn(name="task_status_id")
    private TaskStatus taskStatus;

}

Project

public class Project {

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

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

    @OneToMany(mappedBy = "project", fetch = FetchType.EAGER)
    private List<Task> tasks;

    @JsonIgnore
    @ManyToMany(mappedBy = "projects")
    private List<User> users;
}

When I create a new task I send post request but have problem with project_id. I think that my mapping has some problem because request has been written correctly.

ERRORS: [WARN ] 2018-01-27 00:08:41.103 engine.jdbc.spi.SqlExceptionHelper logExceptions (129 ) - SQL Error: 1048, SQLState: 23000 [ERROR] 2018-01-27 00:08:41.104 engine.jdbc.spi.SqlExceptionHelper logExceptions (131 ) - Column 'project_id' cannot be null

It's example my JSON POST request:

{
   "name":"newTask",
   "title":"newTaskTitle",
   "project":[
      {
         "id":1,
         "name":"projectName"
      }
   ],
   "taskStatus":[
      {
         "id":1,
         "name":"taskStatusName"
      }
   ]
}

Solution

  • I'd say it's because your DB's project_id FK is set to not nullable you have the @JsonIgnore annotation to your Project attribute; You do send the project in your JSON request, but it's simply being ignore by Hibernate/JPA so it stays null and violates your non-nullable DB constraint. Moreover, if the DB field is not nullable, I would suggest you add "nullable=false" to your JoinColumn just in case Hibernate/JPA tries to do something funny.

    If you DO remove the annotation, you most probably will get into a DetachedEntityException of some sort. Bidirectional are a conceptually nice, but a pain to deal with in both JSON and Hibernate; you can check my answer to a very similar question/problem.