如果找不到实体,则为空对象

时间:2012-04-27 08:21:27

标签: java hibernate jpa

我正在使用Hibernate和JPA。我有一个名为Customer的实体引用ParentCustomer

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

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

    // ...
}

但在我的数据库中,有些客户没有父母,因此ParentCustomerID设置为0。我测试课程时得到的例外是:

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

当ID为ParentCustomer时,有没有办法将null设置为0

1 个答案:

答案 0 :(得分:19)

试试这个

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