我遇到了Hibernate和Spring关于延迟加载的常见问题。特别是我可以使用Criteria进行查询,它可以访问bean属性。如果我这么简单地“加载”:
@Override
public Ordine prendiOrdine(int id) {
Session sess = sessionFactory.getCurrentSession();
Ordine res = (Ordine) sess.load(Ordine.class, id);
return res;
}
使用以下bean Ordine:
package it.jsoftware.jacciseweb.beans;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
@Entity
@Table(name="Ordini")
public class Ordine{
int id;
String codice;
InfoLicenza infoLicenza; //Dati sul cliente necessari alla creazione della licenza
double costoOrdine;
Date data;
boolean confermato;
Utente utente;
static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm dd/MM/yyyy");
@Id
@GeneratedValue
@Column(name="ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="CODICE")
public String getCodice() {
return codice;
}
public void setCodice(String codice) {
this.codice = codice;
}
@Transient
public InfoLicenza getInfoLicenza() {
return infoLicenza;
}
public void setInfoLicenza(InfoLicenza infoLicenza) {
this.infoLicenza = infoLicenza;
}
@Column(name="COSTOORDINE")
public double getCostoOrdine() {
return costoOrdine;
}
public void setCostoOrdine(double costoOrdine) {
this.costoOrdine = costoOrdine;
}
@Column(name="DATA")
public Date getData() {
return data;
}
@Transient
public String getFormatData(){
return sdf.format(getData());
}
public void setData(Date data) {
this.data = data;
}
@Column(name="CONFERMATO")
public boolean isConfermato() {
return confermato;
}
public void setConfermato(boolean confermato) {
this.confermato = confermato;
}
public static Ordine creaNuovo(){
Ordine nuovo = new Ordine();
nuovo.confermato = false;
nuovo.data = new Date();
return nuovo;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="UTENTE")
public Utente getUtente() {
return utente;
}
public void setUtente(Utente utente) {
this.utente = utente;
}
}
早在我尝试访问视图层中的Codice属性时就会出现问题(这可能不是一个......)。
我明白了:
org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是org.hibernate.LazyInitializationException:无法初始化代理 - 没有会话
我读到许多人提出的OpenSessionInViewFilter
解决方案,我试过这个:
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>mySessionFactory</param-value>
</init-param>
</filter>
我把它放在web.xml中,就像servlet-context.xml一样,它给出了它不知道标签过滤器的错误。