简体   繁体   English

如何使用一对多数据库结构映射一对一的休眠实体?

[英]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. 当我保存父对象时,它不会填充子对象上的customer_id。 I can't figure out why. 我无法弄清楚为什么。 I'm hoping there is some way to tell it to do this through a hibernate annotation. 我希望有一些方法可以通过hibernate注释告诉它这样做。

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" 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. 我们使用lombok并在对象上进行JSON序列化。 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 );

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

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