我试图让Hibernate @OneToOne注释使用2个类,Hito和Portada。 Portada表具有Hito的外键,一个名为hito的int属性。 我的实体看起来像这样:
日塔:
@Entity
@Table(name = "hito")
public class Hito implements Serializable {
//...other attributes
private Portada portada;
//...getters and setters from other attributes
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "hito")
public Portada getPortada(){ return portada;}
public void setPortada(Portada portada){ this.portada = portada;}
}
拉波尔塔达:
@Entity
@Table(name = "portada")
public class Portada {
//...other attributes
private Hito hito;
//...getters and setters from other attributes
@OneToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "hito")
public Hito getHito() {return hito;}
public void setHito(Hito hito) {this.hito = hito;}
}
当我调用hito.getPortada()时,我期待一个Portada对象,但它返回null。
有什么建议吗? 先谢谢
答案 0 :(得分:4)
我尝试用代码重现您的问题:
@MappedSuperclass
public abstract class BaseEntity {
@Id @GeneratedValue
private Long id;
@Version
private long version;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
}
@Entity
@Table(name = "portada")
public class Portada extends BaseEntity {
//...other attributes
@OneToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "hito")
private Hito hito;
//...getters and setters from other attributes
public Hito getHito() {return hito;}
public void setHito(Hito hito) {this.hito = hito;}
}
@Entity
@Table(name = "hito")
public class Hito extends BaseEntity implements Serializable {
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "hito")
private Portada portada;
public Portada getPortada(){ return portada;}
public void setPortada(Portada portada){ this.portada = portada;}
}
// app:
Portada p = new Portada();
Hito h = new Hito();
p.setHito(h);
h.setPortada(p);
entityManager.persist(h);
entityManager.flush();
entityManager.clear();
Hito h2 = entityManager.find(Hito.class, h.getId());
System.out.println(h2.getPortada().toString());
tx.commit();
最后find
生成的sql:
select
hito0_.id as id1_4_0_,
hito0_.version as version2_4_0_,
portada1_.id as id1_7_1_,
portada1_.version as version2_7_1_,
portada1_.hito as hito3_7_1_
from
hito hito0_
left outer join
portada portada1_
on hito0_.id=portada1_.hito
where
hito0_.id=?
一切都对我有用......
编辑:唯一的区别是我喜欢将字段属性放在字段而不是属性上,但在这个问题上并不重要。请检查是否将两个类添加到persistance.xml或hibernate config。