我正在为已经开发的 Spring Boot Web 应用程序添加一个功能。具有子实体的主要实体是记录。它有一些列/变量,我现在希望它们位于它自己的独立实体 (CustomerOrder) 中,并与记录以一对一的关系存在。总结一下:
记录 {
- 事情 1
- 事情 2
- 事情 3
}
现在变成:
顾客订单 {
- 事情 1
- 事情 2
- 事情 3
}
记录{客户订单}
我对我制作的东西有一些问题。这是 CustomerOrder 模型的相关关系数据:
@Entity
@Table(name="customer_orders")
public class CustomerOrder {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
... other columns
@OneToOne(orphanRemoval = true, cascade = CascadeType.ALL, mappedBy="customerOrder", fetch = FetchType.EAGER)
private Record record;
}
然后这里是 Record 模型的相关数据:
@Entity
@Table(name="records")
public class Record extends Auditable<String> implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
... other columns
@OneToOne
@JoinColumn(name="customer_order_id", nullable = false, unique = true)
private CustomerOrder customerOrder;
}
当我尝试发布记录时,当用户尝试在 ui 中创建记录时,我的问题存在。这是记录的 POST 方法:
@PostMapping
public ResponseEntity<?> saveRecord(@RequestBody Record recordBody, BindingResult result) {
if(!result.hasErrors()) {
if(recordBody.getHardwareItems().isEmpty()) {
record = recordsService.save(recordBody);
} else {
// Save the record first, recordId is required on hardwareItems
// TODO: investigate Spring Hibernate/JPA rules - is there a way to save parent before children to avoid a null recordId
CustomerOrder customerOrder = recordBody.getCustomerOrder();
recordBody.setCustomerOrder(new CustomerOrder());
customerOrder.setRecord(record);
customerOrder = customerOrdersService.save(customerOrder);
record = recordsService.save(recordBody);
}
} else {
return new ResponseEntity<>(result.getAllErrors(), HttpStatus.BAD_REQUEST);
}
// Return the location of the created resource
uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{recordId}").buildAndExpand(record.getId()).toUri();
return new ResponseEntity<>(uri, HttpStatus.CREATED);
}
我收到的错误如下:
2021-02-19 02:35:50.989 WARN 31765 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1364, SQLState: HY000
2021-02-19 02:35:50.989 ERROR 31765 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : Field 'record_id' doesn't have a default value
这至少对我来说是有意义的,因为我正在尝试保存依赖于 Record 对象的 CustomerOrder 对象,该对象尚未被持久化。那么,我该如何更改订单和/或创建和保存 Record 对象,以便我可以将 CustomerOrder 对象保存到其中?
另外,我正在使用 mysql,这是我已经拥有的迁移脚本。我必须在这里为 customer_orders 表添加一些东西吗?
-- Add a sample user
INSERT IGNORE INTO users (first_name, last_name, email, password, enabled, role)
VALUES ('Sample', 'User', 'sample@email.com', 'sample password', true, 'ROLE_ADMIN');
-- Customer Reference Values
INSERT IGNORE INTO customers (name) VALUES ('value1');
INSERT IGNORE INTO customers (name) VALUES ('value2');
INSERT IGNORE INTO customers (name) VALUES ('value3');
INSERT IGNORE INTO customers (name) VALUES ('value4');
INSERT IGNORE INTO customers (name) VALUES ('value5');
INSERT IGNORE INTO customers (name) VALUES ('value6');
INSERT IGNORE INTO customers (name) VALUES ('value7');
INSERT IGNORE INTO customers (name) VALUES ('value8');
这是 Records 表和 CustomerOrders 表的 mysql 脚本:
-- -----------------------------------------------------
-- Table `myapp`.`records`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `myapp`.`records` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`customer_order_id` BIGINT NOT NULL,
`record_id` BIGINT NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `UK_7m7wsqy68b7omkufvckoqv2hf` (`customer_order_id` ASC) VISIBLE,
INDEX `FKta31a9q1llknlo2n0jw741987` (`customer_id` ASC) VISIBLE,
CONSTRAINT `FK3q3clytyrx7s8edp9ok821j3`
FOREIGN KEY (`customer_order_id`)
REFERENCES `myapp`.`customer_orders` (`id`),
CONSTRAINT `FKta31a9q1llknlo2n0jw741987`
FOREIGN KEY (`customer_id`)
REFERENCES `myapp`.`customers` (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 27
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;
-- -----------------------------------------------------
-- Table `myapp`.`customer_orders`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `myapp`.`customer_orders` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`record_id` BIGINT NOT NULL,
`record_id_test` BIGINT NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `UK_ilew9pg8y4qnyhmjg38k1fev2` (`record_id_test` ASC) VISIBLE,
INDEX `FK5rpb3u59bblj7h70wjr5mvb01` (`record_id` ASC) VISIBLE,
CONSTRAINT `FK5rpb3u59bblj7h70wjr5mvb01`
FOREIGN KEY (`record_id`)
REFERENCES `myapp`.`records` (`id`),
CONSTRAINT `FKk7a0g7djyhymr54ehoftkhyfw`
FOREIGN KEY (`record_id_test`)
REFERENCES `myapp`.`records` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;