简体   繁体   English

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

[英]JPA: How to save two entities that have one-to-one relation?

Suppose you have the following two entities, Address and Customer, which have a one-to-one mapping between them. 假设您有以下两个实体,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
}

Additionally, I have these two repository classes: 另外,我有这两个存储库类:

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

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

I also have test like below: 我也有如下测试:

    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 )

As you might expect, the test fails. 正如您所料,测试失败了。 The exception is also more or less expected: 例外或多或少也是预期的:

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

I tried switching the order of the two saves, but as expected, it didn't work. 我尝试切换两个保存的顺序,但正如预期的那样,它不起作用。 So, what is the solution to this problem? 那么,这个问题的解决方案是什么?

Many thanks. 非常感谢。

@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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM