gpt4 book ai didi

java - JPA:如何保存具有一对一关系的两个实体?

转载 作者:搜寻专家 更新时间:2023-11-01 02:25:21 25 4
gpt4 key购买 nike

假设您有以下两个实体,Address 和 Customer,它们之间具有一对一的映射关系。

@Entity
public class Address {
@Id @GeneratedValue
private Long id;
private String street_1;
private String street_2;
private String city;
private String state;
private String zipcode;
private String country;

@OneToOne(mappedBy = "address")
private Customer customer;

//getters, setters, and constructors
}

@Entity
public class Customer {

@Id @GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;

@OneToOne @JoinColumn( name = "address_id" )
private Address address;

//getters, setters, and constructors
}

另外,我有这两个存储库类:

public interface AddressRepository extends CrudRepository<Address, Long> {
}

public interface CustomerRepository extends CrudRepository<Customer, Long> {
List<Customer> findByLastName(String lastName);
List<Customer> findByFirstName(String lastName);
}

我也有如下测试:

    Customer customer = new Customer('Jon', 'Doe')
Address address = new Address(street_1: '1700 Sunlight Ave', state: 'CA',
city: 'Boulder', zipcode: '12345', country: 'USA')
customer.address = address
address.customer = customer
customerRepository.save( customer )
addressRepository.save( address )

如您所料,测试失败了。异常也或多或少是意料之中的:

org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : foo.bar.model.Customer.address -> foo.bar.model.Address

我尝试调换两次保存的顺序,但正如预期的那样,它没有用。那么,这个问题的解决方案是什么?

非常感谢。

最佳答案

@Entity
public class Address {
@Id @GeneratedValue
private Long id;
private String street_1;
private String street_2;
private String city;
private String state;
private String zipcode;
private String country;

@OneToOne(mappedBy = "address")
private Customer customer;

//getters, setters, and constructors
}

@Entity
public class Customer {

@Id @GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;

@OneToOne(cascade = CascadeType.ALL) @JoinColumn( name = "address_id" )
private Address address;

//getters, setters, and constructors
}

关于java - JPA:如何保存具有一对一关系的两个实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25112962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com