davioooh
davioooh

Reputation: 24706

Null object if entity not found

I'm working with Hibernate and JPA. I have an entity called Customer that references a ParentCustomer:

public class Customer {
    @Id
    @GeneratedValue
    @Column(name = "CustomerID")
    private int id;

    @ManyToOne
    @JoinColumn(name = "ParentCustomerID")
    private Customer parent;

    // ...
}

But in my db there are some customers that have no parent so the ParentCustomerID is set to 0. The exception I get when I test my class is:

javax.persistence.EntityNotFoundException: Unable to find it.keyforup.pat.data.entities.Customer with id 0

Is there a way to set the ParentCustomer to null when id is 0?

Upvotes: 6

Views: 10130

Answers (1)

Bitmap
Bitmap

Reputation: 12538

Try this

@ManyToOne
@JoinColumn(name = "ParentCustomerID")
@NotFound(action = NotFoundAction.IGNORE)
private Customer parent;

Upvotes: 21

Related Questions