简体   繁体   English

appedBy作为拥有关系的字段

[英]mappedBy as the field that owns the relationship

I think I understood what the attribute mappedBy means if put in a @OneToMany field (ie 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). 我想我明白了什么属性mappedBy意味着,如果放在一个@OneToMany字段(即表示字段的类型表中有一个外键,该表中申报@OneToMany(mappedBy="...")但我不不能完全理解其语法(或者最终理解其含义->矛盾)。

According to the documentation : 根据文档

mappedBy 的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? mappedby的值应该匹配什么?在哪个表中匹配?

Check out this example . 看看这个例子 There are two classes involved in the one-to-many relationship in this example: Stock and StockDailyRecord . 在此示例中,一对多关系涉及两个类: StockStockDailyRecord Notice the @OneToMany stockDailyRecords field in class Stock : 注意Stock类中的@OneToMany stockDailyRecords字段:

@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. 所以在这种情况下,它说,该领域stockStockDailyRecord类(不要与混淆类Stock )拥有的关系。 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 (eg stock for Stock ). 这种情况也是很常见的,因为你会被那场的类名的小写按照惯例(如指对对方关系的名称stockStock )。

So the mappedBy attribute is actually owned by the StockDailyRecord class. 因此, mappedBy属性实际上归StockDailyRecord类所有。 So that means that the StockDailyRecord will handle persisting the stockDailyRecords referenced in the Stock class. 因此,这意味着StockDailyRecord将处理持久stockDailyRecordsStock类中引用的stockDailyRecords

The name referenced in the mappedBy attribute value is a class field name, not a table column name. mappedBy属性值中引用的名称是类字段名称,而不是表列名称。

And this is how the StockDailyRecord side of that relationship looks: 这是该关系的StockDailyRecord端的外观:

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

Hope this helps, I know its confusing :) 希望这会有所帮助,我知道它令人困惑:)

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

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