简体   繁体   English

@OneToOne 关系 Spring 数据 JPA/Hibernate 实体关系

[英]@OneToOne Relationship Spring Data JPA/Hibernate Entity Relationship

I'm working on adding a feature to an already developed spring boot web application.我正在为已经开发的 spring 启动 web 应用程序添加一个功能。 The primary entity that has child entities is a Record.具有子实体的主要实体是记录。 It has a few columns/variables that I want to now be in its own, separate entity (CustomerOrder) and exist in a one-to-one relationship with the Record.它有一些列/变量,我现在希望它们位于它自己的独立实体 (CustomerOrder) 中,并与记录以一对一的关系存在。 To summarize:总结一下:

Record {记录 {

  • thing 1事情 1
  • thing 2事情 2
  • thing 3事情 3

} }

is now becoming:现在变成:

CustomerOrder {顾客订单 {

  • thing 1事情 1
  • thing 2事情 2
  • thing 3事情 3

} }

Record { CustomerOrder }记录{客户订单}

I'm having some issues with what I've produced.我对我制作的东西有一些问题。 Here is the CustomerOrder model's relevant relationship data:这是 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;


}

And then here is the Record model's relevant data:然后这里是 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;
}

My issue exists when I try to POST a record, when a user tries creating one in the ui.当我尝试发布记录时,当用户尝试在 ui 中创建记录时,我的问题存在。 Here is the POST method for a record:这是记录的 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);
    }

The error I receive is the following:我收到的错误如下:

2021-02-19 00:46:28.398  WARN 29990 --- [io-8080-exec-10] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1364, SQLState: HY000
2021-02-19 00:46:28.398 ERROR 29990 --- [io-8080-exec-10] o.h.engine.jdbc.spi.SqlExceptionHelper   : Field 'record_id' doesn't have a default value

This makes sense to me at least, since I'm trying to save the CustomerOrder object that depends on a Record object, which has yet to have been persisted.这至少对我来说是有意义的,因为我正在尝试保存依赖于记录 object 的 CustomerOrder object,该记录尚未持久化。 So, how do I go about changing up the order and/or creating and persisting a Record object so that I can then save the CustomerOrder object to it?那么,我如何 go 关于更改订单和/或创建和保存记录 object 以便我可以将 CustomerOrder object 保存到它?

You need to mark your column record_id as AI(AUTO_INCREMENT) in your table definition.您需要在表定义中将您的列record_id标记为AI(AUTO_INCREMENT)

ALTER TABLE records CHANGE record_id INT(6) NOT NULL AUTO_INCREMENT;

Your primary key is record_id , add @Column(name = "record_id", nullable = false)您的主键是record_id ,添加@Column(name = "record_id", nullable = false)

@Entity
@Table(name="records")
public class Record extends Auditable<String> implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "record_id", nullable = false)
    private Long id;

    ... other columns

    @OneToOne
    @JoinColumn(name="customer_order_id", nullable = false, unique = true)
    private CustomerOrder customerOrder;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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