假设我有 2 个表 A 和 B。
Table A: id, code1, code2, code3, code4 (id is the primary key)
Table B: codeID, displayText, someOtherColumn (codeID is the primary key)
code1、code2、code3 和 code4 只是表 B 中的 CodeID
现在我要上课了
class Foo {
@Id
@Column(name="id")
private String id;
//Now How To Get the displayText based on codeID in Table B?
private String code1Display;
private String code2Display;
private String code3Display;
private String code3Display
}
我想我应该使用“SecondaryTable”注释。但从克里斯的回复来看,这是行不通的。那么我应该如何实现我的目标呢?
我只需要读取这些值,而不是保存。
最佳答案
如果未指定列信息,则属性 code1Display、code2Display 等的映射将默认使用主表 A 上的字段“CODE1DISPALY”、“CODE2DISPLAY”等。因此,对于每个属性映射,您需要指定该字段所在的表:
@Column(name = "CODE1", table = "B")
private String code1Display;
辅助表注释用于指定第二个表以及它如何链接到主表。请参阅http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Entities/SecondaryTable 。但就你而言,它很简单:
@SecondaryTable(name = "B", pkJoinColumns=@PrimaryKeyJoinColumn(name="codeID"))
关于java - JPA 如何从另一个表中检索值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20057660/