#java #spring #hibernate #jsf
#java #весна #спящий режим #jsf
Вопрос:
я работаю над проектом, использующим jsf, spring и hibernate. я получаю исключение в одном случае, но я не совсем понимаю причину, по которой у меня возникает эта проблема. можете ли вы дать мне представление о том, что я сделал не так
javax.el.ELException: /views/emissionsa.xhtml @102,171 actionListener="#{emission1Bean.payer()}": org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:111)
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:147)
eeeeeeeeeeeee
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:813)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:301)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:74)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1015)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:652)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1575)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1533)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at net.vo.Salaire_$_javassist_5.getPersonnel(Salaire_$_javassist_5.java)
at controller.Emission1Bean.payer(Emission1Bean.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.el.parser.AstValue.invoke(AstValue.java:261)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
... 34 more
25-Jun-2014 23:42:28.209 SEVERE [http-nio-8084-exec-134] com.sun.faces.context.AjaxExceptionHandlerImpl.handlePartialResponseError org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at net.vo.Salaire_$_javassist_5.getPersonnel(Salaire_$_javassist_5.java)
at controller.Emission1Bean.payer(Emission1Bean.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.el.parser.AstValue.invoke(AstValue.java:261)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:147)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:813)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:301)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:74)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1015)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:652)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1575)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1533)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
emissionsa.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!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://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<title>Facelet Title</title>
<style>
.p tr,.p td
{
border : none;
}
</style>
</h:head>
<h:body style="background-color: #ECF3FD;">
<h:graphicImage value="../../images/header.jpg" style="margin-left: auto;margin-right: auto;"></h:graphicImage>
<ui:include src="menu.xhtml" />
<br/>
<br/>
<h:form id="form">
<p:dataTable id="display" var="listeEmissions" value="#{emission1Bean.listeEmissions}" editable="true" style="margin-bottom:10px" rowKey="#{listeEmissions.dateEmission}" selection="#{emission1Bean.emission}" selectionMode="single">
<f:facet name="header">
Liste des factures émises
</f:facet>
<p:ajax event="rowEdit" listener="#{dtEditView.onRowEdit}" />
<p:ajax event="rowEditCancel" listener="#{dtEditView.onRowCancel}"/>
<p:column headerText="Date Emission">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{listeEmissions.dateEmission}" /></f:facet>
<f:facet name="input"><p:inputText id="modelInput" value="#{listeEmissions.dateEmission}" style="width:100%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="N° Ordre de paiement">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{listeEmissions.nop}" /></f:facet>
<f:facet name="input"><p:inputText value="#{listeEmissions.nop}" style="width:100%" label="Year"/></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="N° Bordereau">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{listeEmissions.nbordereau}" /></f:facet>
<f:facet name="input"><p:inputText value="#{listeEmissions.nbordereau}" style="width:100%" label="Year"/></f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:32px" headerText="Modifier">
<p:commandLink styleClass="ui-icon ui-icon-pencil"/>
</p:column>
<p:column style="width:32px" headerText="Supprimer">
<p:commandLink styleClass="ui-icon ui-icon-trash" action="#{emission1Bean.delete()}" process="@this" update=":form:display">
<f:setPropertyActionListener target="#{emission1Bean.emission}" value="#{listeEmissions}" />
</p:commandLink>
</p:column>
</p:dataTable>
<p:commandButton value="Payer le salaire" update="emissionDetail" oncomplete="PF('emissionDialog').show()" />
<p:dialog header="Paiement du salaire" widgetVar="emissionDialog" modal="true" showEffect="fade" hideEffect="fade" resizable="false">
<p:panel id="emissionDetail" style="border:none;">
<p:panelGrid columns="2" rendered="#{not empty emission1Bean.emission}" columnClasses="label,value" style="border:none;">
<p:accordionPanel>
<p:tab title="Payer le salaire">
<h:panelGrid styleClass="p" columns="2" cellpadding="5">
<h:outputText value="Date paiement: " />
<p:inputText value="#{emission1Bean.datePaiement}"/>
<h:outputText value="Compte Bancaire: " />
<p:selectOneMenu value="#{compteBancaireBean.idCompte}" >
<f:selectItem itemValue="#{null}" itemLabel="--Séléctionner un fournisseur" />
<f:selectItems value="#{compteBancaireBean.listeCompteBancaires}" var="compte"
itemValue="#{compte.idCompte}" itemLabel="#{compte.libelleCompte}" />
<f:ajax listener="#{compteBancaireBean.submit()}"/>
</p:selectOneMenu>
<h:outputText value="N° Chèque: " />
<p:inputText value="#{emission1Bean.ncheque}"/>
<h:outputText value="N° Virement: " />
<p:inputText value="#{emission1Bean.nvirement}"/>
<h:outputText value="N° Avis de virement: " />
<p:inputText value="#{emission1Bean.navis}"/>
</h:panelGrid>
</p:tab>
</p:accordionPanel>
</p:panelGrid>
<p:commandButton value="Valider" icon="ui-icon-circle-check" update="display" onclick="emissionDialog.hide();" actionListener="#{emission1Bean.payer()}"/>
<p:commandButton value="Annuler" icon="ui-icon-arrowreturnthick-1-w" onclick="emissionDialog.hide();"/>
</p:panel>
</p:dialog>
</h:form>
</h:body>
</html>
Emission1Bean.java
@Component
@Scope("view")
public class Emission1Bean {
@Autowired
private SalaireMetier salaireMetier;
@Autowired
private EmissionMetier emissionMetier;
@Autowired
private PaiementMetier paiementMetier;
@Autowired
private FactureMetier factureMetier;
@Autowired
private ComptebancaireMetier comptebancaireMetier;
private List<Emission> listeEmissions;
private Emission emission;
private String dateEmission;
private Salaire salaire;
private Integer nop;
private Integer nbordereau;
private int idCompte;
private String datePaiement;
private Comptebancaire comptebancaire;
private Archive archive;
private Integer ncheque;
private Integer nvirement;
private Integer navis;
@PostConstruct
public void init()
{
listeEmissions = emissionMetier.getAllEmissionsSa();
}
public void payer()
{
Emission e = emissionMetier.getEmission(getEmission().getDateEmission());
SalaireId id = new SalaireId(e.getSalaire().getPersonnel().getCin(),e.getSalaire().getMois().getMois());
Salaire s = salaireMetier.getSalaire(id);
Paiement p = new Paiement();
p.setDatePaiement(getDatePaiement());
p.setSalaire(s);
int c = CompteBancaireBean.submit();
Comptebancaire compte = comptebancaireMetier.getComptebancaire(c);
p.setComptebancaire(compte);
p.setNavis(getNavis());
p.setNcheque(getNcheque());
p.setNvirement(getNvirement());
paiementMetier.insert(p);
}
public int submit()
{
System.out.println(idCompte);
return idCompte;
}
public void delete(){
Emission e = emissionMetier.getEmission(getEmission().getDateEmission());
emissionMetier.delete(getEmission().getDateEmission());
listeEmissions.remove(emission);
emission = null;
SalaireId id1 = new SalaireId(e.getSalaire().getPersonnel().getCin(),e.getSalaire().getMois().getMois());
Salaire sa = salaireMetier.getSalaire(id1);
sa.setEtatSalaire("engage");
salaireMetier.update(sa);
}
public Salaire getSalaire() {
return salaire;
}
public void setSalaire(Salaire salaire) {
this.salaire = salaire;
}
public ComptebancaireMetier getComptebancaireMetier() {
return comptebancaireMetier;
}
public void setComptebancaireMetier(ComptebancaireMetier comptebancaireMetier) {
this.comptebancaireMetier = comptebancaireMetier;
}
public PaiementMetier getPaiementMetier() {
return paiementMetier;
}
public void setPaiementMetier(PaiementMetier paiementMetier) {
this.paiementMetier = paiementMetier;
}
public FactureMetier getFactureMetier() {
return factureMetier;
}
public void setFactureMetier(FactureMetier factureMetier) {
this.factureMetier = factureMetier;
}
public int getIdCompte() {
return idCompte;
}
public void setIdCompte(int idCompte) {
this.idCompte = idCompte;
}
public String getDatePaiement() {
return datePaiement;
}
public void setDatePaiement(String datePaiement) {
this.datePaiement = datePaiement;
}
public Comptebancaire getComptebancaire() {
return comptebancaire;
}
public void setComptebancaire(Comptebancaire comptebancaire) {
this.comptebancaire = comptebancaire;
}
public Archive getArchive() {
return archive;
}
public void setArchive(Archive archive) {
this.archive = archive;
}
public Integer getNcheque() {
return ncheque;
}
public void setNcheque(Integer ncheque) {
this.ncheque = ncheque;
}
public Integer getNvirement() {
return nvirement;
}
public void setNvirement(Integer nvirement) {
this.nvirement = nvirement;
}
public Integer getNavis() {
return navis;
}
public void setNavis(Integer navis) {
this.navis = navis;
}
public Emission getEmission() {
return emission;
}
public void setEmission(Emission emission) {
this.emission = emission;
}
public List<Emission> getListeEmissions() {
return listeEmissions;
}
public void setListeEmissions(List<Emission> listeEmissions) {
this.listeEmissions = listeEmissions;
}
public EmissionMetier getEmissionMetier() {
return emissionMetier;
}
public void setEmissionMetier(EmissionMetier emissionMetier) {
this.emissionMetier = emissionMetier;
}
public String getDateEmission() {
return dateEmission;
}
public void setDateEmission(String dateEmission) {
this.dateEmission = dateEmission;
}
public Integer getNop() {
return nop;
}
public void setNop(Integer nop) {
this.nop = nop;
}
public Integer getNbordereau() {
return nbordereau;
}
public void setNbordereau(Integer nbordereau) {
this.nbordereau = nbordereau;
}
}
я знаю, что проблема, с которой я сталкиваюсь, связана с этой строкой, но я не знаю, что сделать, чтобы это исправить
SalaireId id = new SalaireId(e.getSalaire().getPersonnel().getCin(),e.getSalaire().getMois().getMois());
Редактировать
EmissionDao.java
package dao;
import java.util.List;
import net.vo.Emission;
public interface EmissionDao {
public List getAllEmissions();
public List getAllEmissionsSa(Integer id,Integer m);
public Emission getEmission(String date);
public void insert(Emission emission);
public void update(Emission emission);
public void delete(String date);
}
EmissionHibernateDao
пакет dao;
import java.util.List;
import net.vo.Emission;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;
@Repository
public class EmissionHibernateDao implements EmissionDao{
private List<Emission> listeEmissions;
private Emission emission;
public void init()
{
System.out.println("Méthode d'initiation");
}
/*@Override
public List<Object> getAllEmissions() {
Session session=HibernateUtil.getSession();
try
{
session.beginTransaction();
Query q = session.createQuery("select f.idFacture,f.dateFacture,f.montantFacture,f.etatFacture,e.dateEmission,e.nop,e.nbordereau from Facture f,Emission e where e.facture = f.idFacture and f.etatFacture='émise'");
listeEmissions = q.list();
return listeEmissions;
}
catch(HibernateException e)
{
throw e;
}
finally
{
session.close();
}
}*/
@Override
public List getAllEmissions() {
Session session=HibernateUtil.getSession();
try
{
session.beginTransaction();
Query q = session.createQuery("from Emission as e left join fetch e.facture as f where f.etatFacture = 'emise'");
listeEmissions = q.list();
return listeEmissions;
}
catch(HibernateException e)
{
throw e;
}
finally
{
session.close();
}
}
@Override
public List getAllEmissionsSa(Integer id,Integer m) {
Session session=HibernateUtil.getSession();
try
{
session.beginTransaction();
Query q = session.createQuery("from Emission as e left join fetch e.salaire as s left join fetch s.personnel left join fetch s.mois as m where m.annee.annee =:annee and m.mois =:mois and s.etatSalaire = 'emis' ");
q.setParameter("mois", m);
q.setParameter("annee",id);
listeEmissions = q.list();
return listeEmissions;
}
catch(HibernateException e)
{
throw e;
}
finally
{
session.close();
}
}
@Override
public Emission getEmission(String date) {
Session session = HibernateUtil.getSession();
try
{ System.out.println("eeeeeeeeeeeee");
session.beginTransaction();
Query q = session.createQuery("from Emission as em where em.dateEmission='" date "'");
return (Emission) q.uniqueResult();
}
finally
{
session.close();
}
}
@Override
public void insert(Emission emission) {
Session session = HibernateUtil.getSession();
Transaction tx=null;
try
{
tx = session.beginTransaction();
session.save(emission);
tx.commit();
}
catch(RuntimeException e)
{
if(tx != null)
{
tx.rollback();
}
throw e;
}
finally
{
session.close();
}
}
@Override
public void update(Emission emission) {
Session session = HibernateUtil.getSession();
Transaction tx=null;
try
{
tx=session.beginTransaction();
session.update(emission);
tx.commit();
}
catch(RuntimeException e)
{
if(tx != null)
{
tx.rollback();
}
throw e;
}
finally
{
session.close();
}
}
@Override
public void delete(String date) {
Session session = HibernateUtil.getSession();
Transaction tx = null;
try
{
tx=session.beginTransaction();
emission = (Emission) session.get(Emission.class,date);
session.delete(emission);
tx.commit();
}
catch(RuntimeException e)
{
if(tx != null)
{
tx.rollback();
}
throw e;
}
finally
{
session.close();
}
}
}
Ответ №1:
Это проблема гибернации. У объекта есть поля, объявленные как загруженные с задержкой, но объект не подключен к действительному сеансу гибернации, чтобы запускать прокси для ленивого извлечения данных. Из трассировки стека я не могу быть уверен, вызвана ли эта ошибка e.getSalaire().getPersonnel().getCin()
or .getSalaire().getMois().getMois()
(или, может быть, обеими).
Я не знаю, как вы настроили управление сеансами, вероятно, Spring обрабатывает его. Чтобы решить эту проблему, вы должны повторно подключить объект к действительному сеансу гибернации. Вы можете сделать это, используя HibernateTemplate#refresh
метод из классов интеграции Spring Hibernate.
Комментарии:
1. я не знаю, как использовать шаблон гибернации, можете ли вы подробнее объяснить, как я мог это сделать. Для этого вопроса я решил его с помощью getEmission().getSalaire().getPersonnel().getCin() но я снова получаю ту же проблему в другом компоненте, и она не исправляется, даже если я это сделаю. @Луиджи Мендоса
2. Пожалуйста, напишите, как yiu определяет ваши классы dao.