JPA 2:使用非定向OneToMany关系保存实体时违反参照完整性约束

时间:2014-01-20 19:30:35

标签: java hibernate jpa spring-data

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

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

enter image description here 当然我在表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表中创建相关记录{1}}表。

但我有一个例外:

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得到了相同的结果。

我失败的地方?

1 个答案:

答案 0 :(得分:1)

您没有设置此双向关联的另一面:

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)