16

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!

BasicCoder
  • 1,661
  • 10
  • 27
  • 42
  • 2
    What, precisely, is your question? – mcfinnigan Jan 12 '12 at 17:21
  • I don't want to have a exception when I call user.getPerson if there is no reference in table person for the user. I need to check if user.getPerson is not null I want to user.getPerson().getPin(). – BasicCoder Jan 12 '12 at 17:24
  • its a one-to-one not on a primary key. – BasicCoder Jan 12 '12 at 17:27
  • It's not a one-to-one on primary key. You have a foreign key (login) in the T_USER table which references the person ID. Do you have values in this column that are not existing person IDs? – JB Nizet Jan 12 '12 at 17:41
  • try adding the parameter "fetch=FetchType.LAZY" to your @OneToOne annotationo of Person in User – mcfinnigan Jan 12 '12 at 17:41
  • The annotation worked like a charm: @NotFound(action = NotFoundAction.IGNORE) I used this for a log's table, where haven't forced integrity reference. – Joao Polo May 10 '13 at 18:16

1 Answers1

32

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.

C0deAttack
  • 24,419
  • 18
  • 73
  • 81
  • wouaw, thanks, I never saw thoses annotations. It works! Now, its the best solution...? Normaly, I know is better to use one-to-one on primary key but in this case I will use another way with @NotFound annotation. – BasicCoder Jan 12 '12 at 18:25