0

I have an app using Hibernate backed by PostgreSQL.

I have a first Department class:

class Department {

    ...

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "department")
    @Cascade({ CascadeType.SAVE_UPDATE, CascadeType.DELETE_ORPHAN })
    Collection<User> getUsers() {
        return users;
    }
}

Then I have a User class:

class User {

    ...

    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumn(name="user_guid", referencedColumnName="guid")
    @MapKey(name="deviceGuid")
    @Cascade({ CascadeType.ALL, CascadeType.DELETE_ORPHAN })
    public Map<String, Device> getDevices() {
        return devices;
    }
}

And then I have a Device class, without any link back for now:

class Device {
    ...
}

To remove a user, I just remove it from the Collection of User in the Department and cascading does the job of cleaning the orphaned user.

Now, I would like all the Device instances in the Map to be deleted as well, but that does not happen. So I get the classic error:

Caused by: java.sql.BatchUpdateException: Batch entry 0 update equipment.device set user_guid=null where user_guid='88a5b24c-b20f-4aa4-93d0-36fafed0f3c1' was aborted. Call getNextException to see the cause.

What am I doing wrong?

I am using PostgreSQL, Hibernate 3.4.0, JPA 1.0.2.

Thanks!

Antoine Roux
  • 140
  • 1
  • 9

1 Answers1

0

Well, I finally found the answer.

The issue was that my Device class was like that:

Device {

    ...

    @ManyToOne(optional=false, fetch = FetchType.LAZY)
    @JoinColumn(name="user_guid", referencedColumnName="guid")
    public UserDO getUser() {
        return user;
    }
}

So both User and Device had a @JoinColumn annotation. Which means both sides ows the relationship. Which is stupid. Just removing the @JoinColumn from User solved the issue.

So now, user is like that (note the new mappedBy property):

@OneToMany(cascade=CascadeType.ALL, fetch = FetchType.LAZY, mappedBy="user")
@MapKey(name="deviceGuid")
public Map<String, Device> getDevices() {
    return devices;
}

And here is the Stackoverflow question that helped me find the answer: Can someone please explain mappedBy in hibernate?

Community
  • 1
  • 1
Antoine Roux
  • 140
  • 1
  • 9