我有一个lazyInitialization问题,尝试使用<p:graphicImage>
类型将图像(BLOB)从mysql数据库加载到StreamedContent
(Primefaces)。我正在使用JSF + Spring + Hibernate,当我尝试加载图像时,我得到org.hibernate.LazyInitializationException
。这是代码。感谢名单。
这是Backing Bean:
public class AccueilBean implements Serializable {
private CategorieService categorieService;
private List<Categorie> categories;
private StreamedContent dbImg;
public AccueilBean(){
}
@PostConstruct
public void init() {
this.categories = new ArrayList<Categorie>();
categories=categorieService.listerCategorie();
}
public List<Categorie> getCategories(){
return this.categories;
}
public CategorieService getCategorieService() {
return categorieService;
}
public void setCategorieService(CategorieService categorieService) {
this.categorieService = categorieService;
}
public StreamedContent getDbImg() {
InputStream dbStream = null;
dbImg = null;
FacesContext context = FacesContext.getCurrentInstance();
Categorie cat = context.getApplication().evaluateExpressionGet(context, "#{cat}", Categorie.class);
Long id = cat.getId();
Categorie ctg_aux = categorieService.getCategorie(id);
System.out.println(ctg_aux.getImage());
try {
dbStream = ctg_aux.getImage().getBinaryStream();
dbImg = new DefaultStreamedContent(dbStream,"image/jpeg");
}
catch (SQLException e) {System.out.println("erreur");}
return dbImg;
}
}
这是.xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<body>
<h:form>
<p:dataGrid columns="3" var="cat" value="#{accueilBean.categories}">
<p:column>
<p:graphicImage value="#{accueilBean.dbImg}" >
</p:graphicImage>
</p:column>
</p:dataGrid>
</h:form>
</body>
</html>
以下是Categorie实体的映射;
<class name="tn.projet.model.Categorie" table="CATEGORIE">
<id name="id" type="java.lang.Long">
<column name="ID" />
<generator class="increment" />
</id>
<property name="nom" type="java.lang.String">
<column name="NOM" />
</property>
<property name="desc" type="java.lang.String">
<column name="DESCRIPTION" />
</property>
<property name="image" type="java.sql.Blob">
<column name="IMAGE" />
</property>
<set name="produits" table="PRODUIT" inverse="false" lazy="true">
<key>
<column name="ID" />
</key>
<one-to-many class="tn.projet.model.Produit" />
</set>
</class>
答案 0 :(得分:0)
Categorie ctg_aux = categorieService.getCategorie(id);
我认为使用上面的行,只有ctg_aux
是加载但不是急切初始化。意思是如果您在Categorie
中有一些集合,则只需加载ctg_aux
即可加载该集合。实际访问该集合时,它将在以后延迟加载。但是会话必须是开放的(实体必须处于持久状态),同时访问该集合。但是,如果实体处于分离状态,您将看到该问题。
我想在您检索实体后立即在ctg_aux.getImage()
内调用categorieService.getCategorie
方法也应该让hibernate加载该字段。
<强>更新强>
以下内容:
<property name="image" type="java.sql.Blob">
<column name="IMAGE" />
</property>
尝试设置lazy="false"
:
<property name="image" type="java.sql.Blob" lazy="false">
<column name="IMAGE" />
</property>