班级客户:
package com.sdzee.tp.beans;
public class Client implements java.io.Serializable {
private Integer id;
private String nom;
private String prenom;
private String adresse;
private String telephone;
private String email;
private String image;
public Integer getId() {
return id;
}
public void setId( Integer id ) {
this.id = id;
}
public void setNom( String nom ) {
this.nom = nom;
}
public String getNom() {
return nom;
}
public void setPrenom( String prenom ) {
this.prenom = prenom;
}
public String getPrenom() {
return prenom;
}
public void setAdresse( String adresse ) {
this.adresse = adresse;
}
public String getAdresse() {
return adresse;
}
public String getTelephone() {
return telephone;
}
public void setTelephone( String telephone ) {
this.telephone = telephone;
}
public void setEmail( String email ) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setImage( String image )
{
this.image = image;
}
public String getImage()
{
return image;
}
}
类Commande:
package com.sdzee.tp.beans;
import org.joda.time.DateTime;
public class Commande implements java.io.Serializable {
/* Propriétés du bean */
private Integer id;
private Client client;
private DateTime date;
private Double montant;
private String modePaiement;
private String statutPaiement;
private String modeLivraison;
private String statutLivraison;
public Integer getId() {
return id;
}
public void setId( Integer id ) {
this.id = id;
}
public Client getClient() {
return client;
}
public void setClient( Client client ) {
this.client = client;
}
public DateTime getDate() {
return date;
}
public void setDate( DateTime date ) {
this.date = date;
}
public Double getMontant() {
return montant;
}
public void setMontant( Double montant ) {
this.montant = montant;
}
public String getModePaiement() {
return modePaiement;
}
public void setModePaiement( String modePaiement ) {
this.modePaiement = modePaiement;
}
public String getStatutPaiement() {
return statutPaiement;
}
public void setStatutPaiement( String statutPaiement ) {
this.statutPaiement = statutPaiement;
}
public String getModeLivraison() {
return modeLivraison;
}
public void setModeLivraison( String modeLivraison ) {
this.modeLivraison = modeLivraison;
}
public String getStatutLivraison() {
return statutLivraison;
}
public void setStatutLivraison( String statutLivraison ) {
this.statutLivraison = statutLivraison;
}
}
类ClientDao:
package com.sdzee.tp.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.sdzee.tp.beans.Client;
public class ClientDao {
public void creer( Client client )
{
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
session.save( client );
session.getTransaction().commit();
} catch ( RuntimeException e ) {
if ( trns != null ) {
trns.rollback();
}
e.printStackTrace();
} finally {
session.flush();
session.close();
}
}
public Client trouver( Integer id ) {
Client user = null;
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
String queryString = "from Client where id = :id";
Query query = session.createQuery( queryString );
query.setInteger( "id", id );
user = (Client) query.uniqueResult();
} catch ( RuntimeException e ) {
e.printStackTrace();
} finally {
session.flush();
session.close();
}
return user;
}
@SuppressWarnings( "unchecked" )
public List<Client> lister() {
List<Client> users = new ArrayList<Client>();
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try
{
trns = session.beginTransaction();
users = session.createQuery( "from Client" ).list();
} catch ( RuntimeException e ) {
e.printStackTrace();
} finally {
session.flush();
session.close();
}
return users;
}
public void supprimer( Client client ) {
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
Client user = (Client) session.load( Client.class, new Long( client.getId() ) );
session.delete( user );
session.getTransaction().commit();
} catch ( RuntimeException e ) {
if ( trns != null ) {
trns.rollback();
}
e.printStackTrace();
} finally {
session.flush();
session.close();
}
}
}
类CommandeDao:
package com.sdzee.tp.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.sdzee.tp.beans.Client;
import com.sdzee.tp.beans.Commande;
public class CommandeDao {
public void creer( Commande commande )
{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.save( commande );
transaction.commit();
} catch ( HibernateException e ) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public Client trouver( long id ) {
Client user = null;
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
String queryString = "from Commande where id = :id";
Query query = session.createQuery( queryString );
query.setLong( "id", id );
user = (Client) query.uniqueResult();
} catch ( RuntimeException e ) {
e.printStackTrace();
} finally {
session.flush();
session.close();
}
return user;
}
public List<Commande> lister() {
List<Commande> users = new ArrayList<Commande>();
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
users = session.createQuery( "from Commande" ).list();
} catch ( RuntimeException e ) {
e.printStackTrace();
} finally {
session.flush();
session.close();
}
return users;
}
public void supprimer( Commande commande ) {
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
Client user = (Client) session.load( Client.class, new Integer( commande.getId() ) );
session.delete( user );
session.getTransaction().commit();
} catch ( RuntimeException e ) {
if ( trns != null ) {
trns.rollback();
}
e.printStackTrace();
} finally {
session.flush();
session.close();
}
}
}
class PrechargementFilter:
package com.sdzee.tp.filters;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.sdzee.tp.beans.Client;
import com.sdzee.tp.beans.Commande;
import com.sdzee.tp.dao.ClientDao;
import com.sdzee.tp.dao.CommandeDao;
public class PrechargementFilter implements Filter {
public static final String CONF_DAO_FACTORY =
"daofactory";
public static final String ATT_SESSION_CLIENTS = "clients";
public static final String ATT_SESSION_COMMANDES =
"commandes";
private ClientDao clientDao;
private CommandeDao commandeDao;
public void init( FilterConfig config ) throws
ServletException {
/*
* Récupération d'une instance de nos DAO Client et Commande
*/
}
public void doFilter( ServletRequest req, ServletResponse res,
FilterChain chain ) throws IOException,
ServletException {
/* Cast de l'objet request */
HttpServletRequest request = (HttpServletRequest) req;
/* Récupération de la session depuis la requête */
HttpSession session = request.getSession();
/*
* Si la map des clients n'existe pas en session, alors l'utilisateur se
* connecte pour la première fois et nous devons précharger en session
* les infos contenues dans la BDD.
*/
clientDao = new ClientDao();
commandeDao = new CommandeDao();
if ( session.getAttribute( ATT_SESSION_CLIENTS ) == null )
{
/*
* Récupération de la liste des clients existant, et enregistrement
* en session
*/
List<Client> listeClients = clientDao.lister();
Map<Integer, Client> mapClients = new HashMap<Integer,
Client>();
for ( Client client : listeClients ) {
mapClients.put( client.getId(), client );
}
session.setAttribute( ATT_SESSION_CLIENTS, mapClients
);
}
/*
* De même pour la map des commandes
*/
if ( session.getAttribute( ATT_SESSION_COMMANDES ) == null ) {
/*
* Récupération de la liste des commandes existant, et
* enregistrement en session
*/
List<Commande> listeCommandes = commandeDao.lister();
Map<Integer, Commande> mapCommandes = new HashMap<Integer,
Commande>();
for ( Commande commande : listeCommandes ) {
mapCommandes.put( commande.getId(), commande );
}
session.setAttribute( ATT_SESSION_COMMANDES,
mapCommandes );
}
/* Pour terminer, poursuite de la requête en cours */
chain.doFilter( request, res );
}
public void destroy() {
}
}
类ListeCommandes:
package com.sdzee.tp.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ListeCommandes extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public static final String ATT_COMMANDE = "commande";
public static final String ATT_FORM = "form";
public static final String VUE = "/WEB-INF/listerCommandes.jsp";
public void doGet( HttpServletRequest request,
HttpServletResponse response ) throws ServletException, IOException
{
/*
* À la réception d'une requête GET, affichage de la liste des commandes
*/
this.getServletContext().getRequestDispatcher( VUE
).forward( request, response );
}
}
当我尝试访问listeCommandes时,我有这个例外:
ERROR org.hibernate.LazyInitializationException - could not initialize proxy - no Session
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:167)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:215)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
at com.sdzee.tp.beans.Client_$$_javassist_0.getPrenom(Client_$$_javassist_0.java)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:87)
at org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:104)
at org.apache.el.parser.AstValue.getValue(AstValue.java:183)
at org.apache.el.parser.AstDynamicExpression.getValue(AstDynamicExpression.java:44)
at org.apache.el.parser.AstCompositeExpression.getValue(AstCompositeExpression.java:50)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185)
at org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:1026)
at org.apache.jsp.WEB_002dINF.listerCommandes_jsp._jspx_meth_c_005fout_005f0(listerCommandes_jsp.java:379)
at org.apache.jsp.WEB_002dINF.listerCommandes_jsp._jspx_meth_c_005fforEach_005f0(listerCommandes_jsp.java:311)
at org.apache.jsp.WEB_002dINF.listerCommandes_jsp._jspx_meth_c_005fotherwise_005f0(listerCommandes_jsp.java:267)
at org.apache.jsp.WEB_002dINF.listerCommandes_jsp._jspx_meth_c_005fchoose_005f0(listerCommandes_jsp.java:197)
at org.apache.jsp.WEB_002dINF.listerCommandes_jsp._jspService(listerCommandes_jsp.java:111)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
at com.sdzee.tp.servlets.ListeCommandes.doGet(ListeCommandes.java:26)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.sdzee.tp.filters.PrechargementFilter.doFilter(PrechargementFilter.java:89)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
FOR ZEUS
这是listercommande.jsp
<%@ page pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="joda" uri="http://www.joda.org/joda/time/tags"
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Liste des commandes existantes</title>
<link type="text/css" rel="stylesheet" href="<c:url
value="/inc/style.css"/>" />
</head>
<body>
<c:import url="/inc/menu.jsp" />
<div id="corps">
<c:choose>
<%-- Si aucune commande n'existe en session, affichage
d'un message par défaut. --%>
<c:when test="${ empty sessionScope.commandes }">
<p class="erreur">Aucune commande enregistrée.</p>
</c:when>
<%-- Sinon, affichage du tableau. --%>
<c:otherwise>
<table>
<tr>
<th>Client</th>
<th>Date</th>
<th>Montant</th>
<th>Mode de paiement</th>
<th>Statut de paiement</th>
<th>Mode de livraison</th>
<th>Statut de livraison</th>
<th class="action">Action</th>
</tr>
<%-- Parcours de la Map des commandes en session,
et utilisation de l'objet varStatus. --%>
<c:forEach items="${ sessionScope.commandes }"
var="mapCommandes" varStatus="boucle">
<%-- Simple test de parité sur l'index de
parcours, pour alterner la couleur de fond de chaque ligne du
tableau. --%>
<tr class="${boucle.index % 2 == 0 ? 'pair' :
'impair'}">
<%-- Affichage des propriétés du bean
Commande, qui est stocké en tant que valeur de l'entrée courante
de la map --%>
<td><c:out value="${
mapCommandes.value.client.prenom } ${
mapCommandes.value.client.nom }"/></td>
<td><joda:format value="${
mapCommandes.value.date }" pattern="dd/MM/yyyy HH:mm:ss"/></td>
<td><c:out value="${
mapCommandes.value.montant }"/></td>
<td><c:out value="${
mapCommandes.value.modePaiement }"/></td>
<td><c:out value="${
mapCommandes.value.statutPaiement }"/></td>
<td><c:out value="${
mapCommandes.value.modeLivraison }"/></td>
<td><c:out value="${
mapCommandes.value.statutLivraison }"/></td>
<%-- Lien vers la servlet de suppression, avec
passage de la date de la commande - c'est-à-dire la clé de la Map
- en paramètre grâce à la balise <c:param/>. --%>
<td class="action">
<a href="<c:url
value="/suppressionCommande"><c:param name="idCommande" value="${
mapCommandes.key }" /></c:url>">
<img src="<c:url
value="/inc/supprimer.png"/>" alt="Supprimer" />
</a>
</td>
</tr>
</c:forEach>
</table>
</c:otherwise>
</c:choose>
</div>
</body>
</html>
答案 0 :(得分:1)
在检索所需的所有数据之前,您似乎已关闭了HibernateSession。有几种方法可以解决这个问题。请查看以下链接:Hibernate LazyInitializationException while using collection in Spring JSP page
答案 1 :(得分:0)
在你的* .hbm.xml文件中添加lazy = false,或者当你从db获取对象时可以在Hibernate.init(Object)中初始化你的对象