简体   繁体   中英

Spring Boot - java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails

I am getting this error and I cannot solve this problem.

There were plenty of StackOverflow answers based on this topic, but neither one fits me.

The goal is to save Todo and afterwards save TaskTodo (connecting table of Task and Todo ).

I tried to save and flush Todo and afterwards save TaskTodo , but it failed.

Can someone tell me where is the problem?

ERROR:

java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails ( todo . task_todo , CONSTRAINT FK8dn0kderp1dame65xsokdaavj FOREIGN KEY ( todo_id ) REFERENCES todo ( id ))

Assignement - Parent abstract class:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Assignment {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String name;

}

Todo - Domain class:

@Entity
public class Todo extends Assignment {

    private boolean isChecked;

    @OneToMany(mappedBy = "todo")
    Set<TaskTodo> taskTodoSet;
}

Task - Domain class:

@Entity
public class Task extends Assignment {

    private String description;

    @OneToMany(mappedBy = "task")
    public
    Set<TaskTodo> taskTodoSet;

    public Task() {}

    public Task(String name) {
        this.setName(name);
    }
}

TaskTodo - domain class:

@Entity
public class TaskTodo {

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

    @ManyToOne
    @JoinColumn(name = "task_id")
    Task task;

    @ManyToOne
    @JoinColumn(name = "todo_id")
    Todo todo;

    public TaskTodo(Task task, Todo todo) {
        this.task = task;
        this.todo = todo;
    }
}

Service function for saving Todo and TaskTodo:

@Override
public void saveTodo(Todo todo, Long taskId) {
    Task task = getTaskById(taskId);
    todoRepository.saveAndFlush(todo);
    TaskTodo taskTodo = new TaskTodo(task, todo);
    taskTodoRepository.save(taskTodo);
}

I managed to figure out what is the problem

Service function should look like this:

@Override
public void saveTodo(Todo todo, Long taskId) {
    Task task = getTaskById(taskId);
    todo = todoRepository.saveAndFlush(todo); // This line is changed
    TaskTodo taskTodo = new TaskTodo(task, todo);
    taskTodoRepository.save(taskTodo);
}

Reason is because Todo which was sent as parameter did not have id in itself and because of that there was an error.

When I put todo = todoRepository.saveAndFlush(todo); , saveAndFlush returned object which had id in itself. Because of that TaskTodo could be saved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM