Bas*_*der 14 java hibernate exception 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;
}
Run Code Online (Sandbox Code Playgroud)
如果表T_USER中没有特定PERSON的项,user.getPerson会抛出异常:
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [packagename.com.entity.Person#scabriou]
Run Code Online (Sandbox Code Playgroud)
但是如果我在db中的两个表之间有引用,那么getter就可以了!
C0d*_*ack 30
我不能说这是否是最好的解决方案,但你可以使用@NotFound
注释.例如
@NotFound(action = NotFoundAction.IGNORE)
private Person person;
Run Code Online (Sandbox Code Playgroud)
我相信人会留下来null
,不会抛出异常.
归档时间: |
|
查看次数: |
12225 次 |
最近记录: |