6

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?

davioooh
  • 23,742
  • 39
  • 159
  • 250
  • 3
    why you say 0? If you want the entity to be `null`, then the foreign key value should be `null`. – Boris Strandjev Apr 27 '12 at 08:23
  • I'm working on a db used by a third party application, this application set the parent id to 0 when there is no parent for a customer... so I would make sure that every time the parent is not found the `parent` property is set to null. – davioooh Apr 27 '12 at 08:27
  • 1
    However this is not legitimate database behaviour. Furthermore if strict database restriction validation was implied they couldn't even do that.. – Boris Strandjev Apr 27 '12 at 08:30
  • I assume that u are using the key column **primitive** type and that's why **0** gets inserted instead of **NULL** It is not such good idea as told http://stackoverflow.com/q/10110081/507864. – ManuPK Apr 27 '12 at 08:34
  • 1
    Exact duplicate - http://stackoverflow.com/questions/4676594/hibernate-many-to-one-foreign-key-default-0 – Petar Minchev Apr 27 '12 at 08:35
  • @ManuPK Is there such thing as primitive type in sql? – Boris Strandjev Apr 27 '12 at 08:36
  • @BorisStrandjev: I was referring to the **bean mapping** in Java. – ManuPK Apr 27 '12 at 11:08

1 Answers1

20

Try this

@ManyToOne
@JoinColumn(name = "ParentCustomerID")
@NotFound(action = NotFoundAction.IGNORE)
private Customer parent;
Bitmap
  • 12,402
  • 16
  • 64
  • 91
  • This was suggested in the exact duplicate I posted. – Petar Minchev Apr 27 '12 at 08:56
  • As it happends, I've had this issue in the past and resolved with the notfound annotation, so when I saw the thread - it was kind of been on a treadmill - decided to post the answer straight away before someone beat me to it. Didn't see the duplicate post at first hand- Good call. – Bitmap Apr 27 '12 at 09:01
  • There is an edge case when you need LAZY fetch. Hibernate's `@NotFound` annotation just ignores `fetch = FetchType.LAZY` in `@ManyToOne` annotation. Just check this out https://stackoverflow.com/questions/38097248/hibernate-lazy-loading-issue. – Wood Jun 14 '23 at 13:22