带有引用键的 Hibernate 一对一映射错误为空

Hibernate One-To-One mapping error with reference key was null

我有 2 class 客户和 Passport 具有 1-1 关系。 我希望 Passport table 将存储它的所有者 ID (Customer_Id)。 但是保存到数据库后 Customer_Id 总是空的,我的配置有什么问题。

客户Class

@Entity
public class Customer {
    private int id;
    private String name;
    private Passport passport;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public int getId() {
        return id;
    }

    @OneToOne(cascade = CascadeType.ALL, mappedBy="customer")
    public Passport getPassport() {
        return this.passport;
    }
}

护照Class

@Entity
public class Passport {

    private int id;
    private String name;

    private Customer customer;
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public int getId() {
        return id;
    }

    @OneToOne
    @JoinColumn(name="customer_fk")
    public Customer getCustomer() {
        return customer;
    }
}

单元测试Class

public class CustomerTest extends BaseTest {
    @Autowired
    private ICustomerService customerService;

    @Test
    public void saveTest() {
        Customer customer = new Customer();
        customer.setName("Nguyễn Thành Trung");
        Passport passport = new Passport();
        passport.setName("Trung passport");
        customer.setPassport(passport);
        customerService.save(customer);
    }
}

Hibernate: insert into public.Customer (name) values (?)
Hibernate: insert into public.Passport (customer_fk, name) values (?, ?)

而 PostgreSQL 中的结果 tables

客户Table

|--Id---|--------Name--------|
|---1---|-Nguyễn Thành Trung-|

护照Table

|--Id---|--------Name--------|----customer_fk---|
|---1---|-Nguyễn Thành Trung-|------------------|

你可以看到 customer_fk 是空的,这是我的问题。 抱歉我的英语不好。

您的单元测试需求

passport.setCustomer(customer);