具有 UUID 关系的实体错误:外键约束失败。 java 弹簧

问题描述 投票:0回答:1

我正在尝试保存任务卡实体

任务卡服务:

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);
}

控制器

@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));
}

认证获取用户服务:

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

实体用户:

@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;
...
}

实体任务卡:

@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;
}...`

错误

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\]

数据库中一切正常,插入具有有效 UUID 用户的任务卡时成功,插入无效任务卡时出错

我已经尝试以传统方式实例化和设置任务卡对象,而不使用创建的自定义构造函数

打印变量

此印刷服务的示例:

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'}
同一个物体!

java spring-boot foreign-keys uuid
1个回答
0
投票

问题解决了! 我在使用flyway迁移创建数据库表时失败了,这是id的类型,我使用了VARCHAR(36),现在更改为BINARY(16)用户表和任务卡,问题得到解决。我应该发布架构。

© www.soinside.com 2019 - 2024. All rights reserved.