Je suis coincé à cause d'une erreur stupide quelque part, mais je n'arrive pas à comprendre!
Hibernate 4.2.6
J'ai fait référence à cette question, posée plusieurs fois précédemment, par exemple ici
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">true</property>
<property name="hibernate.current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property>
<mapping resource="Event.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
Event.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.db.pojo.Event" table="Events">
<id name="id" column="Id">
<generator class="native"></generator>
</id>
<property name="title" column="Title"></property>
<property name="date" column="Date" type="timestamp"></property>
</class>
</hibernate-mapping>
HibernateUtil
package com.db.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
// TODO Auto-generated method stub
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties());
return configuration.buildSessionFactory(serviceRegistryBuilder
.buildServiceRegistry());
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Chaque fois que j'essaye ceci:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Je reçois :
Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured!
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.Java:988)
at test.EventManager.createAndStoreEvent(EventManager.Java:27)
at test.EventManager.main(EventManager.Java:17)
Modifié après exécution sur mon ordinateur portable personnel
Maintenant, je me méfie du dtd - les pots Hibernate 3.0 sont-ils référés quelque part tandis que les fichiers locaux sont ignorés, même si SYSTEM est spécifié? J'ai obtenu l'exception précédente (pas de contexte actuel) lors de l'exécution du code sur une machine avec un accès Internet restreint. Mais quand j'ai exécuté la même chose sur mon ordinateur portable personnel:
eventDesciption : Team eventDate : 2013-12-12
Nov 28, 2013 8:55:59 PM org.hibernate.annotations.common.reflection.Java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Nov 28, 2013 8:55:59 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.6.Final}
Nov 28, 2013 8:55:59 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Nov 28, 2013 8:55:59 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Nov 28, 2013 8:55:59 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: hibernate.cfg.xml
Nov 28, 2013 8:55:59 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: hibernate.cfg.xml
Nov 28, 2013 8:55:59 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: resources/Event.hbm.xml
Nov 28, 2013 8:55:59 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Nov 28, 2013 8:55:59 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Nov 28, 2013 8:55:59 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
Nov 28, 2013 8:55:59 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
Nov 28, 2013 8:55:59 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/test]
Nov 28, 2013 8:55:59 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****}
Nov 28, 2013 8:56:00 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Nov 28, 2013 8:56:00 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Nov 28, 2013 8:56:00 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Nov 28, 2013 8:56:00 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Nov 28, 2013 8:56:00 PM org.hibernate.internal.SessionFactoryImpl buildCurrentSessionContext
ERROR: HHH000302: Unable to construct current session context [org.hibernate.context.ThreadLocalSessionContext]
org.hibernate.service.classloading.spi.ClassLoadingException: Unable to load class [org.hibernate.context.ThreadLocalSessionContext]
at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.Java:152)
at org.hibernate.internal.SessionFactoryImpl.buildCurrentSessionContext(SessionFactoryImpl.Java:1544)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.Java:516)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.Java:1790)
at com.db.util.HibernateUtil.buildSessionFactory(HibernateUtil.Java:19)
at com.db.util.HibernateUtil.<clinit>(HibernateUtil.Java:9)
at test.EventManager.createAndStoreEvent(EventManager.Java:27)
at test.EventManager.main(EventManager.Java:17)
Caused by: Java.lang.ClassNotFoundException: Could not load requested class : org.hibernate.context.ThreadLocalSessionContext
at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.Java:319)
at Java.lang.ClassLoader.loadClass(Unknown Source)
at Java.lang.ClassLoader.loadClass(Unknown Source)
at Java.lang.Class.forName0(Native Method)
at Java.lang.Class.forName(Unknown Source)
at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.Java:149)
... 7 more
Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured!
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.Java:988)
at test.EventManager.createAndStoreEvent(EventManager.Java:27)
at test.EventManager.main(EventManager.Java:17)
À ma connaissance, votre configuration n'est pas appropriée pour la session en cours. Au lieu de
<property name="hibernate.current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property>
utilisation
<property name="hibernate.current_session_context_class">thread</property>
Pour plus d'informations à ce sujet, veuillez visiter ce lien:
Surtout, lisez les dernières lignes du dernier paragraphe.
Pour ceux qui utilisent Hibernate 4.1,
<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>
Essayez de changer
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
à :
Session session = HibernateUtil.getSessionFactory().openSession();
Vous devez changer votre propriété:
org.hibernate.context.internal.ThreadLocalSessionContext à Thread
Pour hibernate 4.x, vous devez utiliser org.hibernate.context.internal.ThreadLocalSessionContext au lieu de org.hibernate.context.ThreadLocalSessionContext.
Cependant, vous pouvez simplement définir la propriété sur thread et non Thread .
<property name="hibernate.current_session_context_class">thread</property>
Je sais que c'est un vieux post mais juste au cas où quelqu'un viendrait ici comme moi - ça marche:
package com.spring.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static HibernateUtil instance = new HibernateUtil();
private SessionFactory sessionFactory;
private HibernateUtil(){
this.sessionFactory = buildSessionFactory();
}
private synchronized static SessionFactory buildSessionFactory() {
return new Configuration().configure().buildSessionFactory();
}
public static HibernateUtil getInstance() {
if(instance == null){
return new HibernateUtil();
}
return instance;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Maintenant, invoquer ceci est assez simple:
SessionFactory sessionFactory = HibernateUtil.getInstance().getSessionFactory();
Et la prochaine étape serait quelque chose comme ci-dessous:
public void saveOrUpdate(MyObject myObj) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.saveOrUpdate(myObj);
session.getTransaction().commit();
}
Assurez-vous également que hibernate.cfg.xml se trouve dans le dossier src/main/resources.