繁体   English   中英

JPA 2:在保存具有无方向OneToMany关系的实体时违反了引用完整性约束

[英]JPA 2: Referential integrity constraint violation while saving entity with undirectional OneToMany relationship

我正在研究一些体育赛事模型的数据库设计和Java实现。 我有两个实体: GameParticipant ,它们之间是无方向的OneToMany关系。 Game可以有很多Participant

在数据库中,它看起来像:

在此处输入图片说明 当然我对表event_participant有FK约束:

CONSTRAINT `FK_par_eve_eve_id__eve_id`
    FOREIGN KEY (`event_id`)
    REFERENCES `event` (`id`));

在Java代码中,我编写了此映射(简化):

@Entity
@Table(name = "event")
public class GameEntity extends AbstractPersistable<Long> implements Game {
    @Nullable
    @OneToMany(cascade = CascadeType.PERSIST, mappedBy = "game")
    private List<ParticipantEntity> participants;
}

@Entity
@Table(name = "event_participant")
public class ParticipantEntity extends AbstractPersistable<Long> implements GameParticipant {
    @ManyToOne
    @JoinColumn(name="event_id", referencedColumnName = "id", insertable = true)
    private GameEntity game;
}

测试:

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;
}

当我尝试保存新的GameEntity对象(其中包含刚创建的Participant对象)时,我希望Hibernate在event表中创建一条新记录,在event_participant表中创建相关记录。

但我有一个例外:

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, ?, ?, ?, ?)

此插入查询包含event_id字段的NULL值。 我不明白为什么。 当我删除数据库约束时,一切正常, event_id列具有正确的值。

所有样板都由Spring Data util类完成。 我正在使用JPA 2.0,mysql-connector-java 5.1.28,hibernate-entitymanager 4.0.1.Final,spring-data-jpa 1.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)那样为参与者设置外键字段

暂无
暂无

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

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