I have 2 class Customer and Passport with 1-1 relationship. I want Passport table will store it's owner Id (Customer_Id). But after save to database the Customer_Id alway be null, what wrong with my configure.
Customer 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;
}
}
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;
}
}
Unit Test 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 (?, ?)
And the result in PostgreSQL tables
Customer Table
|--Id---|--------Name--------|
|---1---|-Nguyễn Thành Trung-|
Passport Table
|--Id---|--------Name--------|----customer_fk---|
|---1---|-Nguyễn Thành Trung-|------------------|
You can see the customer_fk is null and that is my broblem. Sorry about my bad english.
Your unit test needs
passport.setCustomer(customer);