我有2级客户和护照,有1-1关系。 我希望Passport表将存储它的所有者Id(Customer_Id)。 但保存到数据库后,Customer_Id总是为空,我的配置有什么问题。
客户类
@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;
}
}
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;
}
}
单元测试类
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表中
客户表
| --id --- | -------- --------名称|
| --- 1 --- |-NguyễnThànhTrung-|
护照表
| --id --- | -------- --------名称| ---- --- customer_fk |
| --- 1 --- |-NguyễnThànhTrung-| ------------------ |
您可以看到customer_fk为null,这是我的问题。 抱歉我的英文不好。
答案 0 :(得分:0)
您的单元测试需要
passport.setCustomer(customer);