Hibernate one-to-one, No row with the given identifier exists exception

BasicCoder picture BasicCoder · Jan 12, 2012 · Viewed 13.2k times · Source

I need a link between two entities, so I use a one-to-one

@Entity
@Table(name = "T_USER")
public class User implements Serializable {

    @Id
    @Column(name = "user_id")
    private int userId;

    @Column(name = "login")
    private String login;

    @OneToOne(optional = true)    
    @JoinColumn(name="login", referencedColumnName="person_id", nullable = true, insertable = false, updatable = false)
    private Person person;
}

@Entity
@Table(name = "T_PERSON")
public class Person implements Serializable {
    @Id
    @Column(name = "person_id")
    private String personId;

    @Column(name = "pin")
    private String pin;
}

If there is no item for a particulary PERSON in table T_USER, user.getPerson throw a exception:

org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [packagename.com.entity.Person#scabriou]

But If I have reference between the 2 tables in the db, the getter works!

Answer

C0deAttack picture C0deAttack · Jan 12, 2012

I can't say if this the best solution but you could use the @NotFound annotation. E.g.

@NotFound(action = NotFoundAction.IGNORE)
private Person person;

I believe person will remain null and the exception will not be thrown.