2

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」と思います。すべてが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。ロードする DB には何もありません。

SQL はすべて Hibernate によって生成されるため、DDL にエラーがある場合は、Java コードのエラーが原因であることは間違いありません。

4

0 に答える 0