[SPRING 2.5][Hibernate]Problème de session: LazyInitializationException:no session
Bonjour,
Pour situer mon contexte, je développe actuellement dans le cadre d'une application java SE, un programme qui permet de sauvegarder dans une base de données toutes les requêtes posées par des utilisateurs pour générer des stats. Les données sont lues depuis des fichiers XML et stockées dans une base de données Mysql.
J'utilise JPA, les annotations Spring et Hibernate.
Grace à mes anciens posts et vos réponses, j'ai pu utiliser les annotations Spring pour me faire injecter les beans services dans mon main afin d'invoquer les différentes méthodes sur une Personne.
Voici mon problème :
J'ai une relation many to many entre une personne et une requête :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
@Entity
@Table(name = "PERSONNE")
public class Personne implements Serializable {
// champs
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@SuppressWarnings("unused")
@Version
@Column(name = "VERSION", nullable = false)
private int version;
@Column(name = "ID_Personne", nullable = false, unique = true)
private int id_personne;
@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.LAZY)
@JoinTable(name = "PERSON_REQUEST", joinColumns = @JoinColumn(name = "PERSON_ID"), inverseJoinColumns = @JoinColumn(name = "REQUEST_ID"))
private Set<Request> requests = new HashSet<Request>(); |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
@Entity
@Table(name = "REQUEST")
public class Request implements Serializable {
// ID
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "DATE", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date date;
// relation inverse Request -> PErsonne
@ManyToMany(mappedBy = "requests", cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.LAZY)
private Set<Personne> Personnes = new HashSet<Personne>(); |
Dans mon Main, lorsque j'essaye de rajouter une requête à la liste des requêtes posées par une personne :
Code:
1 2 3 4 5 6 7 8 9 10
|
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
// couche service
IService service = (IService) ctx.getBean("service");
Personne person = new Personne(id_personne);
Request requete = new Request(id_request);
person.getRequests().add(requete);
request.getPersonnes().add(person);
service.savePersonne(person); |
J'ai une exception qui me dit que la session a été fermée !
Code:
1 2 3 4 5 6 7 8 9 10 11
|
15:26:04,673 ERROR LazyInitializationException:19 - failed to lazily initialize a collection of role: fr.pack.entites.Personne.requests, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: fr.pack.entites.Personne.requests, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:343)
at org.hibernate.collection.PersistentSet.add(PersistentSet.java:189)
at fr.stime.test.TrackLoader.PersistFile(TrackLoader.java:180)
at fr.stime.test.TrackLoader.run(TrackLoader.java:75)
at fr.stime.test.InitDB.callTrackLoader(InitDB.java:92)
at fr.stime.test.InitDB.main(InitDB.java:52) |
J'ai cherché sur les forum et dans la doc Spring mais je n'ai pas trouvé une réponse claire à ma question!
Avez-vous une idée comment résoudre ce problème ?
Voic mon fichier de configuration Spring :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="jdbc.properties" />
</bean>
<context:annotation-config />
<context:component-scan base-package="fr.pack.dao" />
<context:component-scan base-package="fr.pack.service" />
<context:component-scan base-package="fr.pack.manager" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- <property name="showSql" value="true" />-->
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="generateDdl" value="true" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop><!-- validate | update | create | create-drop-->
</props>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
<!-- la source de donnéees DBCP -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- le gestionnaire de transactions -->
<tx:annotation-driven transaction-manager="txManager" />
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- traduction des exceptions -->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<!-- persistence -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
</beans> |
Merci beaucoup par avance de votre réponse.
[SPRING 2.5][Hibernate]Problème de session: LazyInitializationException:no session
Salut djo.mos,
Merci de m'avoir encore répondu.
Non, j'ai mis les bonnes annotations que tu m'as indiqué la dernière fois.
Voici mon service et mon DAO
/************** DAO ***************/
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
@Repository
@Transactional
public class DaoImpl implements Dao {
private static final Logger LOG = Logger.getLogger(DaoImpl.class);
@PersistenceContext
private EntityManager em;
// get Personne by Id
public PDV getPersonne(Long Id) {
return em.find(Personne.class, Id);
}
// get Personne by Id_Personne
@SuppressWarnings("unchecked")
public PDV getPersonneById(int id_Personne) {
PDV result = null;
Session hibSession = (Session) em.getDelegate();
Criteria criteria = hibSession.createCriteria(Personne.class).add(Restrictions.eq("id_Personne", id_personne));
List<Personne> _results = criteria.list();
if (_results != null && _results.size() == 0) {
System.err.println("getPersonneById: No entity found for query");
}
else
result = _results.get(0);
return result;
}
// save Personne
public Personne savePersonne(Personne personne) {
em.persist(personne);
return personne;
}
// update Personne
public Personne updatePersonne(Personne personne) {
return em.merge(personne);
}
// delete Personne
public void deletePersonne(Long Id) {
Personne pdv = em.find(Personne.class, Id);
if (pdv == null) {
throw new DaoException(-1);
}
em.remove(pdv);
}
// get all Personne
@SuppressWarnings("unchecked")
public List<Personne> getAllPersonne() {
return em.createNamedQuery("get All Personne").getResultList();
}
// get all Request of Personne
@SuppressWarnings("unchecked")
public List<Request> getAllRequestsOfPersonne(Long pdvId) {
return em.createNamedQuery("get all Request of PDV").setParameter("Id_personne", pdvId).getResultList();
} |
/****************SERVICE *******************/
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
@Service("service")
public class ServiceImpl implements IService {
// couche [dao]
private Dao dao;
public Dao getDao() {
return dao;
}
@Autowired
public void setDao(Dao dao) {
this.dao = dao;
}
// get Personne by Id
public Personne getPersonne (Long id) {
return dao.getPersonne (id);
}
// get Personne by IdPDV
public Personne getPersonne ById(int pdv) {
return dao.getPersonne ById(pdv);
}
// save Personne
public Personne savePersonne (Personne pdv) {
return dao.savePersonne (pdv);
}
// update Personne
public Personne updatePersonne (Personne pdv) {
return dao.updatePersonne (pdv);
}
// delete Personne
public void deletePersonne (Long id) {
dao.deletePersonne (id);
}
// get all Personne
@SuppressWarnings("unchecked")
public List<Personne > getAllPersonne () {
return dao.getAllPersonne ();
}
// get all Request of Personne
@SuppressWarnings("unchecked")
public List<Request> getAllRequestsOfPersonne (Long pdvId) {
return dao.getAllRequestsOfPersonne (pdvId);
} |
Merci pour votre aide