![](/img/trans.png)
[英]How to access object in case of shared primary key as one-to-one relationship in JPA?
[英]Spring Boot Data JPA: One-to-One Relationship with Shared Primary Key
我是 Spring 引導數據 JPA 的新手。 我正在測試Customer
和Phone
實體之間與共享主鍵的一對一關系:
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
@OneToOne(mappedBy = "customer")
@PrimaryKeyJoinColumn
private Phone phone;
// Constructors, getters, and setters
}
@Entity
public class Phone {
@Id
private Long id;
private String number;
@OneToOne
@MapsId
@JoinColumn(name = "id")
private Customer customer;
// Constructors, getters, and setters
}
這是application.properties
:
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/springtest?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.show-sql=true
當我運行簡單測試時:
@SpringBootTest
class SpringTestApplicationTests {
@Autowired
private CustomerRepository customerRepository;
@Autowired
private PhoneRepository phoneRepository;
@Test
public void test() {
customerRepository.deleteAll();
phoneRepository.deleteAll();
final Customer customer = new Customer();
customer.setFirstName("John");
customer.setLastName("Doe");
customerRepository.save(customer);
final Phone phone = new Phone();
phone.setNumber("1234567890");
phone.setCustomer(customer);
phoneRepository.save(phone);
}
}
最后一行代碼( phoneRepository.save(phone)
)拋出此異常:
org.springframework.dao.InvalidDataAccessApiUsageException:
detached entity passed to persist: org.code.entities.Customer
我已經廣泛搜索了異常,但仍然無法解決問題。 我很感激任何幫助。
一些可能有用的附加信息:
我能夠讓它工作。 這是細節。 Customer
和Phone
實體之間的關系是雙向的和一對一的。 請注意, Phone
是關系的擁有方,因為它的主鍵不是自動生成的,而且它的主鍵也是Customer
實體的外鍵。 實例化這些實體后,我們必須通過以下行交叉引用另一個中的每個 object:
phone.setCustomer(customer);
customer.setPhone(phone);
然后,我們必須先保存手機 object,然后保存客戶 object。
這是新的測試:
@SpringBootTest
class SpringTestApplicationTests {
@Autowired
private CustomerRepository customerRepository;
@Autowired
private PhoneRepository phoneRepository;
@Test
public void test() {
phoneRepository.deleteAll();
customerRepository.deleteAll();
final Customer customer = new Customer();
customer.setFirstName("John");
customer.setLastName("Doe");
final Phone phone = new Phone();
phone.setNumber("1234567890");
phone.setCustomer(customer);
customer.setPhone(phone);
phoneRepository.save(phone);
customerRepository.save(customer);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.