【发布时间】:2013-08-15 11:22:45
【问题描述】:
我有两张表,比如说 Person 和 Person_info。两个表都有 shared PK person_id,它也用作外键。 情况是,可能存在不存在 Person_info 的 Person。 person_info 对 person 是可选的,不需要存在具有相同 person_id 的行。 当我想搜索休眠的人时,例如:
Criteria criteria = session.createCriteria(Person.class);
criteria.add(Restrictions.eq("name", name));
Object obj = criteria.uniqueResult();
我得到一个例外:
[<package>.PersonInfo#338664] org.hibernate.ObjectNotFoundException: No row with the given identifier exists: <package>.PersonInfo#338664]
当然,person_id=338664 的 Person_info 行确实不存在。但我仍然希望 hibernate 能够处理这个问题。 如果该行存在,那么我想加载它,如果它不存在我想获取 null,不是异常。
我使用的是休眠版本 3.5.6-Final。 我认为这个线程是完全相同的问题,但它没有解决方案@PrimaryKeyJoinColumn with Bidirectional @OneToOne relationship
感谢您的帮助。
带注释的类如下所示:
人物类:
@Entity
@Table(name="Person")
public class Person extends BaseDBEntity<Integer>{
private PersonInfo personInfo;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="person_id")
public Integer getId() {
return id;
}
@OneToOne(cascade = CascadeType.ALL, optional = true)
@PrimaryKeyJoinColumn
public PersonInfo getPersonInfo() {
return personInfo;
}
}
PersonInfo 类:
@Entity
@Table(name="Person_info")
public class PersonInfo extends BaseDBEntity<Integer> {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="person_id")
public Integer getId() {
return id;
}
}
它们都继承自 BaseDBEntity:
public abstract class BaseDbEntity<T> implements Serializable {
private static final long serialVersionUID = 1L;
protected T id;
}
【问题讨论】:
-
除了 PersonInfo 的 ID 生成,这在我看来是正确的。您是否尝试过使用更新版本的 Hibernate? 3.5.6 已经很老了。
标签: hibernate jpa-2.0 one-to-one