OneToMany-联接表和外键之间有什么区别? [英] OneToMany - what are the differences between join table and foreign key?
问题描述
可以使用@JoinColumn
注释禁用@OneToMany
关系联接表.默认值为联接表.
例如生产系统的优缺点是什么?
我什么时候应该使用联接表,什么时候不该使用?
谢谢.
默认情况下,仅当您使用单向关系时,@OneToMany
才会创建联接表.
换句话说,如果您具有Employee
和Project
实体,并且Employee
实体的定义如下(假定这些实体没有orm.xml
条目):
@Entity
public class Employee {
// ...
@OneToMany
Set<Project> projects;
}
@Entity
public class Project {
// ...
}
JPA提供程序将创建一个联接表(请注意,在@OneToMany
批注中没有mappedBy
属性,因为没有从Project
引用Employee
实体). /p>
另一方面,如果您使用双向关系:
@Entity
public class Employee {
// ...
@OneToMany(mappedBy="employee")
Set<Project> projects;
}
@Entity
public class Project {
// ...
@ManyToOne
Employee employee;
}
将不使用联接表,因为那里将使用许多"侧来存储此关系的外键.
但是,即使在具有定义的mappedBy
属性的双向@OneToMany
关系的情况下,也可以强制使用联接表.您可以使用 @JoinTable
批注来实现关系的拥有者.
如前所述,在默认情况下使用联接表(单向@OneToMany
关系)的情况下,也有可能使用@JoinColumn
.
最好自己测试FK并加入表性能差异.我只能猜测,较少的联接(在本例中为FK)似乎具有更好的性能.
此外,有时DBA会定义数据库模式,而您只需要使映射适合现有模式即可.然后,您无法选择FK或联接表-这就是为什么您可以选择.
There is the possibility to disable the @OneToMany
relationship join table with the @JoinColumn
annotation. The default is a join table.
What are the advantages and disadvantages for a production system for example?
When should I use a join table and when not?
Thank you.
By default @OneToMany
will create a join table only if you'll use unidirectional relationship.
In other words, if you have Employee
and Project
entities and the Employee
entity is defined as follows (assume there is no orm.xml
entries for these entities):
@Entity
public class Employee {
// ...
@OneToMany
Set<Project> projects;
}
@Entity
public class Project {
// ...
}
the JPA provider will create a join table (notice there is no mappedBy
attribute in @OneToMany
annotation as there is no reference to Employee
entity from the Project
).
On the other hand, if you'll use bidirectional relationship:
@Entity
public class Employee {
// ...
@OneToMany(mappedBy="employee")
Set<Project> projects;
}
@Entity
public class Project {
// ...
@ManyToOne
Employee employee;
}
The join table will not be used, as there "many" side will be used to store the foreign key for this relationship.
However, you can force to use join table even in cases when you have bidirectional @OneToMany
relationship with defined mappedBy
attribute. You can achieve it using @JoinTable
annotation on the owning side of the relationship.
There is also a possibility, as you've mentioned, to use @JoinColumn
in case where join table would be used by default (unidirectional @OneToMany
relationship).
It's best to test the FK and join table performance difference for yourself. I can just guess that less joins (in this case: FK) seems to have better performance.
Moreover, sometimes the DBA defines the database schema and you just need to fit your mappings to the existing schema. Then you have no choice over FK or join table - that's why you have a choice.
这篇关于OneToMany-联接表和外键之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!