简体   繁体   中英

How can I map a one-to-one hibernate entity with a one-to-many database structure?

I'm trying to do a one-to-one bi-directional hibernate entity. When I save the parent object it is not filling in the customer_id on the child object. I can't figure out why. I'm hoping there is some way to tell it to do this through a hibernate annotation.

My Entities look like

@Table(name = "customer")
public class CustomerEntity {

    @Id
    @Column(name = "id")
    private Long id;

    @OneToOne(mappedBy = "customer", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private CustomerAddressEntity customerAddress;

    ..more
}

and

@Table(name="customer_address")
@GenericGenerator(name="generator", strategy="increment")
public class CustomerAddressEntity {

    @Id
    @Column(name = "id")
    @GenericGenerator(name = "sequence_customer_address_id", strategy = "com.abc.enrollment.service.IdGenerator")
    @GeneratedValue(generator = "sequence_customer_address_id")
    private Long id;

    @OneToOne
    @JoinColumn(name = "customer_id", referencedColumnName = "id")
    private CustomerEntity customer;

    ..more
}

the tables looks like

CREATE TABLE enroll.customer_address(
id                 NUMBER(38,0) NOT NULL,
customer_id        NUMBER(38,0) )

CREATE TABLE enroll.customer (
id                 NUMBER(38,0) NOT NULL)

hibernateVersion = "5.0.0.CR2"


In addition to the accepted answer I had to do a few other things that got it working. I'll post it here in case it helps someone else. We use lombok and are doing JSON serialization on the object. The following annotations avoided the stack overflow error.

@ToString(exclude = "customer")
@EqualsAndHashCode(exclude = "customer")
public class CustomerAddressEntity {

and

@JsonIgnore
private CustomerEntity customer;

Since it is a bi-directional relation, you should set it at both ends. Meaning, set the reference to the child object in parent and also the reference to the parent object in child. It should work then. Something like this

Customer cust = new Customer();
CustomerAddress custAddr = new CustomerAddress();
cust.setCustomerAddress( custAddr );
custAddr.setCustomer( cust );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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