Search code examples
javahibernateone-to-manymappedby

mappedBy as the field that owns the relationship


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

According to the documentation:

mappedBy

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 mappedby match, and in which table?


Solution

  • 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).

    So 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.

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

    And 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 :)