Java JPA 2:保存具有无向一域关系的实体时违反引用完整性约束
我正在研究一些体育赛事模型的数据库设计和Java实现。 我有两个实体:Java JPA 2:保存具有无向一域关系的实体时违反引用完整性约束,java,hibernate,jpa,spring-data,Java,Hibernate,Jpa,Spring Data,我正在研究一些体育赛事模型的数据库设计和Java实现。 我有两个实体:游戏和参与者以及它们之间的无方向的一对一关系游戏可以有许多参与者 在数据库中,它看起来像: 当然,我对表事件参与者有FK约束: CONSTRAINT `FK_par_eve_eve_id__eve_id` FOREIGN KEY (`event_id`) REFERENCES `event` (`id`)); 我用Java代码编写了这个映射(简化): 此插入查询包含事件id字段的空值。我不明白为什么。 当我
游戏
和参与者
以及它们之间的无方向的一对一关系<代码>游戏可以有许多参与者
在数据库中,它看起来像:
当然,我对表事件参与者有FK约束:
CONSTRAINT `FK_par_eve_eve_id__eve_id`
FOREIGN KEY (`event_id`)
REFERENCES `event` (`id`));
我用Java代码编写了这个映射(简化):
此插入查询包含事件id
字段的空值。我不明白为什么。
当我删除DB约束时,一切正常,event\u id
列具有正确的值
所有样板文件都是由SpringDataUtil类完成的。
我正在使用JPA2.0、mysql连接器java 5.1.28、hibernate entitymanager 4.0.1.Final、spring数据JPA1.3.4.RELEASE和H2数据库进行测试。
我使用H2或MySQL得到了相同的结果
我失败的地方?您没有设置此双向关联的另一端:
public GameEntity addParticipant(TeamEntity team, GameParticipant.Alignment alignment) {
ParticipantEntity pe = ParticipantEntity.create(team, alignment)
participants.add(pe);
pe.setGame(this);
return this;
}
需要注意的是,您没有像在pe.setGame(this)
中那样为参与者设置外键字段addParticipant
看起来怎么样?该方法是否包含参与者。添加(…)
和参与者内容.setGame(此)?
我更新了原始帖子。哦,真丢脸。谢谢你,奥里德。有没有办法不手动操作?
TeamEntity teamHome = teamsDao.findOne(1L);
TeamEntity teamGuest = teamsDao.findOne(2L);
GameEntity newEntity = new GameEntity()
.addParticipant(teamHome, GameParticipant.Alignment.HOME)
.addParticipant(teamGuest, GameParticipant.Alignment.GUEST);
dao.save(newEntity);
public GameEntity addParticipant(TeamEntity team, GameParticipant.Alignment alignment) {
if (participants == null) {
participants = new ArrayList<ParticipantEntity>();
}
participants.add(ParticipantEntity.create(team, alignment));
return this;
}
public static ParticipantEntity create(TeamEntity team, Alignment alignment) {
ParticipantEntity object = new ParticipantEntity();
object.team = team;
object.alignment = alignment;
return object;
}
Referential integrity constraint violation: "FK_PAR_EVE_EVE_ID__EVE_ID: PUBLIC.EVENT_PARTICIPANT FOREIGN KEY(EVENT_ID) REFERENCES PUBLIC.EVENT(ID) (0)"; SQL statement:
insert into event_participant (id, alignment, event_id, participant_id, participant_type) values (null, ?, ?, ?, ?)
public GameEntity addParticipant(TeamEntity team, GameParticipant.Alignment alignment) {
ParticipantEntity pe = ParticipantEntity.create(team, alignment)
participants.add(pe);
pe.setGame(this);
return this;
}