简体   繁体   中英

bi-directional one-to-one in hibernate spring jpa

class Transaction implements Serializable {

    @OneToOne(mappedBy = "transaction")
    @JoinColumn(name = "invoice_id", nullable = false)
    private InvoiceDetails invoice;

    // some other columns, getter and setter
}

class InvoiceDetails implements Serializable {

    @OneToOne(mappedBy = "invoice", fetch = FetchType.LAZY)
    @JoinColumn(name = "transaction")
    private Transaction transaction;

    // some other column and getter setter
}

It get an error while compiling this - Unknown mappedBy in: com.project.model.Transaction.invoice, referenced property unknown: com.project.model.InvoiceDetails.transaction

However, when I remove the mappedBy = "invoice" from InvoiceDetails, it compiles. But, there is column in transactions table which references InvoiceDetails. There is a column in InvoiceDetails which stores the Id from Transaction.

I haven't tried to get the data yet. I am just seeing the columns in database now.

When you have bidirectional relationships in JPA , you should only set mappedBy in one of the properties. the one without mappedBy will have a column with foreign key constraint for the relationship in it's table and the other one will not have any column for that relationship. Because mappedBy indicates that this relationship is been handled by the property you specified in the other side of the relationship.

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