javaspring-bootforeign-keysuuid

Entity with UUID relationship error: a foreign key constraint fails. java spring


I'm trying save TaskCard entity

TaskCard Service:

public TaskCard create(TaskCardCreateData taskCardCreateData) {
    var creator = authenticatedUserService.getAuthenticatedUser();
    var taskCard = new TaskCard(
            taskCardCreateData.title(),
            taskCardCreateData.description(),
            taskCardCreateData.dueDate(),
            creator,
            taskCardCreateData.priority()
    );
    return taskCardRepository.save(taskCard);
}

Controller:

@PostMapping @Transactional public ResponseEntity createTaskCard(@RequestBody @Valid TaskCardCreateData taskCardCreateData, UriComponentsBuilder uriComponentsBuilder){

    var taskCard = taskCardService.create(taskCardCreateData);
    var uri = uriComponentsBuilder.path("/taskcard/{id}").buildAndExpand(taskCard.getId()).toUri();

    return ResponseEntity.created(uri).body(new TaskCardDetailData(taskCard));
}

Authenticated get user service:

public User getAuthenticatedUser() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return (User) authentication.getPrincipal();
}

Entity User:

@Table(name="users")
@Entity(name="User")
public class User implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    private UUID id;

    private String login;
    private String password;

    @OneToMany(mappedBy = "creator")
    private Set<TaskCard> taskCards;
...
}

Entity TaskCard:

@Table(name = "taskcards") @Entity(name = "TaskCard") public class TaskCard {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String description;
private LocalDateTime createdDate;
private LocalDateTime updatedDate;
private LocalDateTime dueDate;

@ManyToOne
@JoinColumn(name = "creator_id")
private User creator;

public TaskCard() {
}

public TaskCard(String title, String description, LocalDateTime dueDate, User creator, String priority) {
    this.title = title;
    this.description = description;
    this.createdDate = LocalDateTime.now();
    this.dueDate = dueDate;
    this.creator = creator;
    this.priority = priority;
    this.status = TaskCardStatus.BACKLOG;
    this.active = true;
}...`

Error:

Hibernate: insert into taskcards (active, created_date, creator_id, description, due_date, priority, status, title, updated_date) values         (?, ?, ?, ?, ?, ?, ?, ?, ?) 
2024-08-27T22:44:36.744-04:00  WARN 35454 --- \[todolu\] \[nio-8080-exec-1\] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1452, SQLState: 23000 2024-08-27T22:44:36.744-04:00 ERROR 35454 --- \[todolu\] \[nio-8080-exec-1\] o.h.engine.jdbc.spi.SqlExceptionHelper   : Cannot add or update a child row: a foreign key constraint fails (todolu.taskcards, CONSTRAINT fk_taskcards_users FOREIGN KEY (creator_id) REFERENCES users (id) ON DELETE CASCADE) 2024-08-27T22:44:36.756-04:00 ERROR 35454 --- \[todolu\] \[nio-8080-exec-1\] o.a.c.c.C.\[.\[.\[/\].\[dispatcherServlet\]    : Servlet.service() for servlet \[dispatcherServlet\] in context with path \[\] threw exception \[Request processing failed: org.springframework.dao.DataIntegrityViolationException: could not execute statement \[Cannot add or update a child row: a foreign key constraint fails (todolu.taskcards, CONSTRAINT fk_taskcards_users FOREIGN KEY (creator_id) REFERENCES users (id\`) ON DELETE CASCADE)\] \[insert into taskcards (active,created_date,creator_id,description,due_date,priority,status,title,updated_date) values (?,?,?,?,?,?,?,?,?)\]; SQL \[insert into taskcards (active,created_date,creator_id,description,due_date,priority,status,title,updated_date) values (?,?,?,?,?,?,?,?,?)\]; constraint \[null\]\] with root cause

java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (todolu.taskcards, CONSTRAINT fk_taskcards_users FOREIGN KEY (creator_id) REFERENCES users (id) ON DELETE CASCADE)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:118) \~\[mysql-connector-j-8.3.0.jar:8.3.0\]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) \~\[mysql-connector-j-8.3.0.jar:8.3.0\]

everything happens normally in the database, success when inserting taskcards with valid UUID users and error when inserting invalid taskcards

I have already tried to instantiate and set the taskcard object in a traditional way without using the custom constructor created

Printing var's

example in service of this printing:

public TaskCard create(TaskCardCreateData taskCardCreateData) {    
var creator = authenticatedUserService.getAuthenticatedUser();
    System.out.println("CREATOR");
    var teste = creator.toString();
    System.out.println(teste);
    var taskCard = new TaskCard(
            taskCardCreateData.title(),
            taskCardCreateData.description(),
            taskCardCreateData.dueDate(),
            creator,
            taskCardCreateData.priority()
    );
    System.out.println("TASKCARD CREATOR");
    var testedois = taskCard.getCreator().toString();
    System.out.println(testedois);
    return taskCardRepository.save(taskCard);
}

CREATOR User{id=66386333-6465-3364-2d31-6665612d3464, login='luiz.jolo', password='$2a$12$FohqZ/qawqsrlhmFH0zoE.SoviWTjKN18Qyi6EnBcfZjm5qLbBn9y'} TASKCARD CREATOR User{id=66386333-6465-3364-2d31-6665612d3464, login='luiz.jolo', password='$2a$12$FohqZ/qawqsrlhmFH0zoE.SoviWTjKN18Qyi6EnBcfZjm5qLbBn9y'} The same object!


Solution

  • Problem solved! Its my fail in the moment of create the database tables with flyway migrations, it's the type of id, i haved used VARCHAR(36) and i change now to BINARY(16) the user table and taskcards and the problem are solved. I should have postes the schema.