Hibernate n:m extractHashCode throws NullPointerException

The problem is that hibernate is trying to save the relationship object, CellAtLocation instance, while the children objects, Cell and/or Location instances are not yet persisted. Thus, children objects don't have generated ids associated with them and therefore hibernate can not compute the hash for them.

Before trying to save CellAtLocation instance, try saving the children objects first by calling saveOrUpdate method on them.


I had the same problem and figured out that the way to properly map embedded ids is by using @Embeddable, @EmbeddedId and @MapsId (which is the one missing in the problem code). The docs from @MapsId annotation states an example that fixes this issue:

Example:

// parent entity has simple primary key

@Entity
public class Employee {
    @Id
    private long employeeId;

    private String name;
    ...
}

// dependent entity uses EmbeddedId for composite key

@Embeddable
public class DependentId {
    private String name;

    private long employeeId;   // corresponds to primary key type of Employee
}

@Entity
public class Dependent {
    @EmbeddedId
    private DependentId dependentId;
    ...
    @MapsId("employeeId")   //  maps the employeeId attribute of embedded id
    @ManyToOne
    private Employee employee;
}

This is the proper way to fix the issue. This way, you wouldn't need to save the entities separately (which is not a good practice). Instead, hibernate will manage the entire transaction for you by mapping the generated ids properly.

Hope this helps for anyone having this issue in the future.

Cheers,


For anyone also dealing with this issue, it occurred in my case simply because I did not have an open and active transaction. The stack trace did not point directly to this being the issue but can be explained as follows:

The parent item was being persisted in the cache and hibernate simply accepted the parent not having an actual ID. If we could have somehow called flush() on our connection we would have then been notified of the non-existent transaction. Instead, when the child item was to be persisted the parent's ID did not TRULY exist. When hibernate went to get the parent's hashed id for the purpose of saving the child, the NPE was thrown.