英文:
Unable to create Mapping Entity with JPA
问题
A. 我有一个类似下面的实体 EntityA:
表 - EntityA(id 长整型 主键, name 字符串)
@Entity @Table
EntityA{
@Id
long id;
String name;
}
B. 基于此,我想通过 JPA 在以下类中获取数据(使用单向映射):
@Entity @Table
EntityMap{
long id;
@OneToOne
EntityA entity;
@OneToMany
List<EntityA> mappedEntity;
}
C. 为了暂时使其工作,我创建了一个类似下面的实体:
表 - entity_map(id 长整型 主键, source_entity_id 长整型 外键-EntityA_id, target_entity_id 长整型 外键-EntityA_id)
@Entity @Table
EntityMap{
@Id
long id;
@OneToOne
@JoinColumn(name = "source_entity_id")
EntityA sourceEntity;
@ManyToOne
@JoinColumn(name = "target_entity_id")
EntityA targetEntity;
}
这样做可以按预期工作,但我需要有关 #B 的实体的解释。有什么建议吗?
英文:
A. I have a entity EntityA like below:
Table - EntityA(id long PK, name varchar)
@Entity @Table
EntityA{
@Id
long id;
String name;
}
B. Based on this I want to fetch data in below class through JPA(using unidirectional mapping):
@Entity @Table
EntityMap{
long id;
@OneToOne
EntityA entity;
@OneToMany
List<EntityA> mappedEntity;
}
C. To make it work for now I have created an entity like below:
Table - entity_map(id long pk, source_entity_id long FK-EntityA_id, target_entity_id long FK-EntityA_id)
@Entity @Table
EntityMap{
@Id
long id;
@OneToOne
@JoinColumn(name = "source_entity_id")
EntityA sourceEntity;
@ManyToOne
@JoinColumn(name = "target_entity_id")
EntityA targetEntity;
}
This is working as expected but I need entity explained in #B. Any suggestion?
答案1
得分: 0
一个 @OneToMany
的关联可以通过以下方式实现:
@JoinColumn(name = "entity_map_id")
@OneToMany
List<EntityA> mappedEntity;
在你的 EntityA
表中,你需要一个名为 entity_map_id
的列,并且有一个 foreign key (entity_map_id) references EntityMap(id)
的约束。
如果你不能改变 EntityA
表,你需要使用 @JoinTable
来执行映射:
@JoinTable(name = "JOIN_TABLE", joinColumns = {@JoinColumn(name = "MY_ENTITY_MAP_FK")}, inverseJoinColumns = {@JoinColumn(name = "ENTITY_A_FK")})
@OneToMany
List<EntityA> mappedEntity;
这个关联表包含两个列:ENTITY_A_FK
和 MY_ENTITY_MAP_FK
:
create table JOIN_TABLE(
ENTITY_A_FK integer not null,
MY_ENTITY_MAP_FK integer not null
);
英文:
A @OneToMany
relationship can be archieved by
@JoinColumn(name = "entity_map_id")
@OneToMany
List<EntityA> mappedEntity;
In your EntityA
table you need a column entity_map_id
and a foreign key (entity_map_id) references EntityMap(id)
constraint.
If you cannot change the EntityA
table you need a @JoinTable
to perform the mapping:
@JoinTable(name = "JOIN_TABLE", joinColumns = {@JoinColumn(name = "MY_ENTITY_MAP_FK")}, inverseJoinColumns = {@JoinColumn(name = "ENTITY_A_FK")})
@OneToMany
List<EntityA> mappedEntity;
The join table contains two columns ENTITY_A_FK
and MY_ENTITY_MAP_FK
:
create table JOIN_TABLE(
ENTITY_A_FK integer not null,
MY_ENTITY_MAP_FK integer not null
);
专注分享java语言的经验与见解,让所有开发者获益!
评论