我试图让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;}
}
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。
有什么建议么?
先谢谢了
最佳答案
我试图用代码重现您的问题:
@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配置中。
关于java - hibernate @OneToOne无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38271111/