nbro nbro - 2 years ago 86
Java Question

mappedBy as the field that owns the relationship

I think I understood what the attribute

means if put in a
field (i.e. the table representing the type of the field has a foreign key to this table that declared
, but I don't understand exactly its syntax (or at the end its meaning -> contradiction).

According to the documentation:


public abstract String mappedBy

The field that owns the relationship.

Required unless the relationship is unidirectional.

Default: ""

Which field is the documentation talking about? What should the value of
match, and in which table?

Answer Source

Check out this example. There are two classes involved in the one-to-many relationship in this example: Stock and StockDailyRecord. Notice the @OneToMany stockDailyRecords field in class Stock:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "stock")
public Set<StockDailyRecord> getStockDailyRecords() {
    return this.stockDailyRecords;

So in this case, its saying that the field stock in the StockDailyRecord class (not to be confused with the class Stock) owns the relationship. What I think makes this more confusing is that in this case, both the name of the field and the class are the same. This sort of case is also very common, since you tend to refer to the name of the relationship on the other side by the lowercase of the class name of that field by convention (e.g. stock for Stock).

Also, the mappedBy attribute is actually owned by the StockDailyRecord class. So that means that the StockDailyRecord will handle persisting the stockDailyRecords referenced in the Stock class.

So the name in referenced in the mappedBy attribute value is a class field name, not a table column name.

This is how the StockDailyRecord side of that relationship looks:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "STOCK_ID", nullable = false)
public Stock getStock() {
    return this.stock;

Hope this helps, I know its confusing :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download