简体   繁体   中英

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 ?

Try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM