Swapnil
Swapnil

Reputation: 8318

org.hibernate.AssertionFailure: null identifier in Hibernate @OneToMany relationship

I've a bidirectional @OneToMany / @ManyToOne relationship in the below entities:

@Entity
public class Item implements java.io.Serializable {

    // other columns including ID
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long itemId;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "packageId")
    private Package package;        
}

@Entity
public class Package {

    // other columns including ID
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany(fetch = FetchType.EAGER, mappedBy="package", cascade = CascadeType.ALL)
    private Set<Item> items = new HashSet<Item>(0);
}    

Suppose initially there's a package without items and to add items to that package, when I try to get a package by its Id packageRepository.findOne(packageId) (Spring Data JPA code), I get the below error at that line.

org.hibernate.AssertionFailure: null identifier
    at org.hibernate.engine.spi.EntityKey.<init>(EntityKey.java:69)
    at org.hibernate.internal.AbstractSessionImpl.generateEntityKey(AbstractSessionImpl.java:247)
    at org.hibernate.loader.Loader.extractKeysFromResultSet(Loader.java:794)
    at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:707)

I think the Hibernate tries a left outer join and finds that itemId (Id for Item entity) is null. I do need to have the EAGER fetch there. What's the workaround for this issue? How do I retrieve a package when there are no items?

Upvotes: 3

Views: 10024

Answers (1)

heikkim
heikkim

Reputation: 2975

Use the @NotFound annotation:

@OneToMany(fetch = FetchType.EAGER, mappedBy="package", cascade = CascadeType.ALL)
@NotFound(action=NotFoundAction.IGNORE)
private Set<Item> items = new HashSet<Item>(0);

This may not be the best cure to your problem. Hibernate docs describe the use of @NotFound as:

When Hibernate cannot resolve the association because the expected associated element is not in database (wrong id on the association column), an exception is raised. This might be inconvenient for legacy and badly maintained schemas. You can ask Hibernate to ignore such elements instead of raising an exception using the @NotFound annotation.

Upvotes: 0

Related Questions