Any way to suppress Hibernate "More than one row with the given identifier" exception?

1.5k Views Asked by At

In our domain model, one Event is designed to have zero or one Notification, so I started to use @OneToOne annotation for entity relation:

class Event {
...
    @OneToOne(mappedBy = "event")
    Notification notification;

In most cases it works fine, but in very rare cases there are duplicate Notifications for a single Event, which differ only by milliseconds in timestamp. If such happens, Hibernate throws an exception:

javax.persistence.PersistenceException: org.hibernate.HibernateException: More than one row with the given identifier was found: 1290338, for class: Xxx

-- and the entire result set fails.

The workaround I implemented: annotate relation as @OneToMany but return a single Notification through a getter:

@OneToMany(mappedBy = "event")
List<Notification> notifications;
...

public Notification getNotification() {
    return notifications == null || notifications.isEmpty()
           ? null : notifications.get(0);
}

It works pretty fine, but the thing I dislike here is that bean style of class is broken. My question: is there Hibernate preference to suppress mentioned exception, so I can manage without custom getter?

Database is managed and populated by outer system, so there is no possibility to add constraint nor control insertion of duplicates.

0

There are 0 best solutions below