Raja Singh
Raja Singh

Reputation: 31

unable to understand mappedby

I have created two entities Customer and Customer Record.

//customer class
@OneToOne
@JoinColumn(name="CUSTREC_ID", unique=true)
CustomerRecord customerRecord;

//customer record class
@OneToOne(mappedBy="customerRecord")
Customer customer;

The purpose of mappedBy is to indicate the owner exists on the other side of the relationship. When I see my example and see that mappedBy is used as mappedBy="customerRecord", I see that it contradicts with the definition of mappedBy because the mapping is done on the customer side of the relationship and the value mentioned for the attribute in mappedBy is customer Record. If I follow the definition of mappedBy then it should have been mappedBy="customer" since that is the side holding the relationship. So what is wrong in my understanding?

Queries generated:
Hibernate: insert into CustomerRecord (customerRecordName, CustomerRecordId) values (?, ?)
Hibernate: insert into Customer (customerName, CUSTREC_ID, customerId) values (?, ?, ?)

Upvotes: 2

Views: 592

Answers (2)

silvanasono
silvanasono

Reputation: 390

In this video, it is explained clearly, if it can help https://www.youtube.com/watch?v=DrmxYYC_hbo

Upvotes: -2

MDaigle
MDaigle

Reputation: 11

Yes, mappedBy causes a lot of confusion, I think because of the inference going on by Hibernate. Here is a simple use case, much like yours, but using a one to many relationship ... i.e. one user may have many accounts, but an account may have only one user:

public class User {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    @OneToMany(fetch = FetchType.LAZY, mappedBy="user")
    private List<Account> accounts = new ArrayList<Account>();
    public List<Account> getAccounts() {
        return Accounts;
    }
    ...
}

public class Account {
    ...
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private User user;
    ...
}

At some point, the User getAccounts() method gets called. Hibernate says, "okay, I see getAccounts returns Account objects, and I see we have a OneToMany join relationship defined in User with Accounts, but I need to know which column in Account I should use to join these two objects (tables)."

@mappedBy tells Hibernate, join the @Id value from this class (User model "id" field) with the @mappedBy value in the distant class (Account model "user" field).

Please let me know if I can help clarify further.

Upvotes: 1

Related Questions