Search code examples
javahibernateinsertunique-constraint

Hibernate - insert breaking unique constraint


I have three tables as below with many to one mapping(help from Jdbc table design which is better)

Emails, Notification and Email_notifications enter image description here

Below is the code for saving

    EmailData e1 = new EmailData();
    e1.setEmail(email);

    NotificationData n1 = new NotificationData();
    n1.setMessage(message);

    EmailNotificationData en1 = new EmailNotificationData("N");
    en1.setEmail(e1);
    en1.setNotification(n1);
    session.save(en1);

so when I add dulplicate email its suppose to update the notification in the email_notifications table -> a new notification for the same email but i get insert error due to unique constraint violation

I tried "saveorupdate " that didnt work too

any suggestions for how to resolve this


Solution

  • The duplicate EmailNotificationData object's id must be same as the previous former duplicate EmailNotificationData obj. Else hibernate wont know whether the duplicate object is already persisted. If id is set for EmailNotificationData obj, hibernate will know the obj is already persisted and hibernate will do and update on the obj. If id is not there, hibernate willl try to save and whatever unique constraints set in db will result in constraint violation exception.