hibernate未设置外键

xjreopfe  于 2021-07-16  发布在  Java
关注(0)|答案(1)|浏览(310)

我有这个模型

public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

@OneToOne
@PrimaryKeyJoinColumn
private Address registred_address_id;

@OneToOne
@PrimaryKeyJoinColumn
private Address actual_address_id;
...

我有这个方法

private Customer addCustomer(String first_name, String last_name, String middle_name, String sex, Address address) {
    Customer customer = new Customer(first_name, last_name, middle_name, sex);
    customer.setActual_address_id(address);
    customer.setRegistered_address_id(address);
    customerRepo.save(customer);
    return customer;
}

但是hibernate没有设置实际地址id和注册地址id(它是onetoone)
hibernate:插入到客户(名字、姓氏、中间名、性别)值(?,?,?)2021-03-18 14:01:58.340 warn 12836---[nio-8080-exec-1]o.h.engine.jdbc.spi.sqlexceptionhelper:sql错误:0,sqlstate:23502 2021-03-18 14:01:58.340 error 12836---[nio-8080-exec-1]o.h.engine.jdbc.spi.sqlexceptionhelper:ошибка: значение 无效的в столбце "注册地址\u id“отношения "“客户”нарушает ограничение 不为空подробности: ошибочная строка содержит (6,空,空,空,空,空,男)。

eqoofvh9

eqoofvh91#

你说的是矛盾的。
从你想要的一边 Customer.id 由数据库在插入后生成。这是什么 GenerationType.IDENTITY 其实我的意思是。
从另一个Angular 你试图使用 @PrimaryKeyJoinColumn 什么意思 Customer.id 应设置为 Address.id . 的正确Map @PrimaryKeyJoinColumn 应该是这样的:

@Entity
public class Customer {

  @Id
  private long id;

  @OneToOne
  @PrimaryKeyJoinColumn
  private Address address;

  public void setAddress(Address address) {
     this.address = address;
     this.id = address.getId();
  }
  // ... 
}

但这不符合你的要求。
因此,我建议您将客户表改为:

create table customer
(
   id bigserial not null,
   reg_address_id bigint,
   act_address_id bigint,
   -- ...
   primary key(id),
   foreign key(reg_address_id) references address(id),
   foreign key(act_address_id) references address(id)
);

然后使用以下Map:

@Entity
public class Customer {

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

  @OneToOne
  @JoinColumn(name = "reg_address_id")
  private Address registredAddress;

  @OneToOne
  @JoinColumn(name = "act_address_id")
  private Address actualAddress;

  // ... 
}

相关问题