Hibernate静默无法插入null FK,没有抛出异常

时间:2012-06-21 18:59:56

标签: hibernate

我遇到了一些Hibernate的问题,我希望它不会抛出异常。简而言之,我有一个实体映射到具有所需FK的表(由Hibernate生成的表);如果在Java中正确指定FK,一切都很顺利。但是,如果省略FK,则实体不会保存到DB。很好 - 但我在session.save()时间,甚至transaction.commit()都没有例外;当我尝试加载实体时,我才意识到这个问题。这使得调试成为一场噩梦。当我提交时,Hibernate 应该发出某种错误吗?

我不知道错误可能来自哪里,所以我不太确定如何包含适当的具体信息。欢迎任何提示。

伪代码:

try {
    tx = session.beginTransaction();

    MyEntity me = new MyEntity();
    me.setName("Foo");
    // Omitting to call me.setSomeFK(someOtherEntity);
    session.save(me);

    tx.commit();
    System.out.println("Everything is OK");
}
catch (Exception e) {
    tx.rollback();
}

可悲的是,它认为“Everything is OK”。一切都确定。


实体代码(样本):

不幸的是我无法展示整件事,但是

GenericParticipantEntity.java

@Entity
@Table
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
    name = "participant_type",
    discriminatorType = DiscriminatorType.STRING,
    length = 16
)
abstract public class GenericParticipantEntity {
    private long participantId;
    private StatEventEntity event;
    private SeasonEventEntity seasonEvent;
    // A bunch of other fields

    @Id
    @Column(name = "participantId")
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long getParticipantId() {
        return participantId;
    }
    public void setParticipantId(long participantId) {
        this.participantId = participantId;
    }

    @ManyToOne(targetEntity = StatEventEntity.class, optional = false)
    @JoinColumn(name = "stat_event_id")
    public StatEventEntity getEvent() {
        return event;
    }
    public void setEvent(StatEventEntity event) {
        this.event = event;
    }

    @ManyToOne
    @JoinColumn(name = "season_event_id", nullable = false)
    public SubSeasonEventEntity getSeasonEvent() {
        return seasonEvent;
    }
    public void setSeasonEvent(SubSeasonEventEntity seasonEvent) {
        this.seasonEvent = seasonEvent;
    }
}

SpecificParticipant.java(这个实际上不包含代码):

@Entity
@DiscriminatorValue("specific1")
public class SpecificParticipant extends GenericParticipantEntity { }

用法:

Transaction tx;
Long id = null;
try {
    tx = session.beginTransaction();
    SpecificParticipant somePlayer = new SpecificParticipant();
    somePlayer.setEvent(someEvent);
    id = session.save(somePlayer);
    tx.commit();
}
catch (Throwable e) {
    if (tx != null) tx.rollback();
    throw e;
}

请注意,我忘记设置seasonEvent属性,因此当然INSERT查询最终会失败 - 应该如此;这是我的错误。让我感到困惑的是,Hibernate在这里不会引发异常;相反,当我尝试根据id加载对象时发现问题,数据库中没有任何内容可以加载。

SQL完全由Hibernate生成,因此如果DDL中存在错误,那肯定是由于Java代码中的错误。

0 个答案:

没有答案