Home > Enterprise >  getting an error when trying to fetch data that is not in the db
getting an error when trying to fetch data that is not in the db

Time:01-26

I am getting this error when trying to fetch a data that does not exist in the database:

org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Referential integrity 
constraint violation: "FK2HQOTYIYWTEUJXLQ0PHEMTLMF: PUBLIC.TBL_TASK FOREIGN 
KEY(USER_ID) REFERENCES PUBLIC.TBL_USER(USER_ID) (CAST(13 AS 

BIGINT))"; SQL

I have 2 entities:

@Table(name = "tbl_task")

public class Task {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long taskId;
private String title;
private String description;
private Status status;

@OneToOne
@JoinColumn(name = "user_id", referencedColumnName = "userId")
private User assignee;


@Table(name = "tbl_user")
 public class User {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
private String name;
@Column(unique = true)
private String email;
private Active active;
private String password;

}

this is the task controller:

    @ResponseStatus(HttpStatus.CREATED)
    public TaskResponse addTask(@Valid @RequestBody Task task){
    return taskService.addTask(task);
   }

The issue is that if a user call addTask() before a user was inserted to the database he gets the error. I attach a screenshot to show the reqest example. How can I make sure that before a user make a request to addTask a user exists in the db? Thank you

screenshot

CodePudding user response:

I'm guessing that you are trying to save a task directly from the data you send. As mentioned in the accepted answer in your previous question, it fails now.

The answer is (almost) in the question. You need to fetch the User first and check that it exists before trying to save the task as you get it from this JSON.

By the way, the error is not when fetching but when inserting data.

  • Related