J'utilise les DAO et le _BaseRootDAO créés par HibernateSynchronizer. J'ai codé ma classe HibernateSessionFactory, et hibernate.cfg.xml est correctement indiqué dans le classpath.
Code non fonctionnel de mon action
Code:
public Gerant(String login, String password) throws DatabaseException, InvalidPasswordException, InvalidLoginException {
List<Gerants> listeGerants = null;
Gerants leGerant = null;
try {
leGerant = GerantsDAO.getInstance().get(new Integer("990286994"));
} catch (org.hibernate.HibernateException e) {
log.error("erreur à la recherche du gérant");
e.printStackTrace();
throw new DatabaseException();
}
}
Si je ne fais pas appel à la méthode initialize(), le code génère cette erreur (dans Tomcat) :
Code:
12:07:14,303 WARN RequestProcessor:516 - Unhandled Exception thrown: class java.lang.RuntimeException
12:07:14,319 ERROR [action]:253 - "Servlet.service()" pour la servlet action a généré une exception
java.lang.RuntimeException: The session factory has not been initialized (or an error occured during initialization)
at fr.integrance.hibernate._BaseRootDAO.getSessionFactory(_BaseRootDAO.java:104)
at fr.integrance.hibernate._BaseRootDAO.getSession(_BaseRootDAO.java:155)
at fr.integrance.hibernate._BaseRootDAO.getSession(_BaseRootDAO.java:126)
at fr.integrance.hibernate._BaseRootDAO.get(_BaseRootDAO.java:260)
at fr.integrance.modele.gerants.base.BaseGerantsDAO.get(BaseGerantsDAO.java:44)
at fr.integrance.modele.gerants.Gerant.<init>(Gerant.java:79)
at fr.integrance.struts.action.LoginAction.execute(LoginAction.java:60)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:419)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
at java.lang.Thread.run(Thread.java:595)
Voici les informations utiles pour comprendre mon problème:
Hibernate version: 3.0.5, HibernateSynchronizer version: 3.1.1, Mapping documents: corrects car je récupère correctement mes objetsProblème: je suis obligé de lancer la méthode
initialize() avant de pouvoir accéder à un de mes objets. Pourquoi???
Code de test JUnit fonctionnel car initialize() appelée :Code:
public class TestHibernate extends TestCase {
private static Logger log = Logger.getLogger(TestHibernate.class);
private static Calendar calendrier = Calendar.getInstance();
public static void main(String[] args) {
junit.textui.TestRunner.run(TestHibernate.class);
}
public final static void testGetGerantWithID() {
Gerants leGerant = null;
try {
fr.integrance.modele.gerants.base.BaseGerantsDAO.initialize();
leGerant = GerantsDAO.getInstance().get(new Integer(990286994));
} catch (HibernateException e) {
e.printStackTrace();
} finally {
assertEquals("a", leGerant.getLoginItutelle());
assertEquals("z", leGerant.getPwdItutelle());
}
}
}
Name and version of the database you are using: mySql 4.1, pas de problème de ce côtéDebug level Hibernate log excerpt:Code:
11:53:13,687 INFO Environment:464 - Hibernate 3.0.5
11:53:13,718 INFO Environment:482 - loaded properties from resource hibernate.properties: {hibernate.max_fetch_depth=1, hibernate.cache.region_prefix=hibernate.test, hibernate.cglib.use_reflection_optimizer=true, hibernate.jdbc.use_streams_for_binary=true, hibernate.c3p0.timeout=5000, hibernate.c3p0.min_size=2, hibernate.c3p0.max_size=2, hibernate.c3p0.max_statements=100}
11:53:13,718 INFO Environment:509 - using java.io streams to persist binary types
11:53:13,718 INFO Environment:510 - using CGLIB reflection optimizer
11:53:13,718 INFO Environment:540 - using JDK 1.4 java.sql.Timestamp handling
11:53:13,828 INFO Configuration:1110 - configuring from resource: /hibernate.cfg.xml
11:53:13,828 INFO Configuration:1081 - Configuration resource: /hibernate.cfg.xml
11:53:14,203 INFO Configuration:444 - Mapping resource: fr/integrance/modele/gerants/Antenne.hbm.xml
11:53:14,374 INFO HbmBinder:260 - Mapping class: fr.integrance.modele.gerants.Antenne -> antenne
11:53:14,390 INFO Configuration:444 - Mapping resource: fr/integrance/modele/gerants/Gerants.hbm.xml
11:53:14,453 INFO HbmBinder:260 - Mapping class: fr.integrance.modele.gerants.Gerants -> gerants
11:53:14,453 INFO Configuration:444 - Mapping resource: fr/integrance/modele/gerants/SupGerants.hbm.xml
11:53:14,499 INFO HbmBinder:260 - Mapping class: fr.integrance.modele.gerants.SupGerants -> sup_gerants
11:53:14,499 INFO Configuration:444 - Mapping resource: fr/integrance/modele/Ad031famille.hbm.xml
11:53:14,578 INFO HbmBinder:260 - Mapping class: fr.integrance.modele.Ad031famille -> ad031famille
11:53:14,593 INFO Configuration:444 - Mapping resource: fr/integrance/modele/Ad042benef.hbm.xml
11:53:14,640 INFO HbmBinder:260 - Mapping class: fr.integrance.modele.Ad042benef -> ad042benef
11:53:14,656 INFO Configuration:444 - Mapping resource: fr/integrance/modele/Adr.hbm.xml
11:53:14,718 INFO HbmBinder:260 - Mapping class: fr.integrance.modele.Adr -> adr
11:53:14,718 INFO Configuration:444 - Mapping resource: fr/integrance/modele/Cod.hbm.xml
11:53:14,734 INFO HbmBinder:260 - Mapping class: fr.integrance.modele.Cod -> cod
11:53:14,749 INFO Configuration:444 - Mapping resource: fr/integrance/modele/Per.hbm.xml
11:53:14,765 INFO HbmBinder:260 - Mapping class: fr.integrance.modele.Per -> per
11:53:14,781 INFO Configuration:444 - Mapping resource: fr/integrance/modele/simulation/TauxSimulation.hbm.xml
11:53:14,796 INFO HbmBinder:260 - Mapping class: fr.integrance.modele.simulation.TauxSimulation -> taux_simulation
11:53:14,796 INFO Configuration:1222 - Configured SessionFactory: fr.integrance.hibernate.HibernateSessionFactory
11:53:14,812 INFO Configuration:875 - processing extends queue
11:53:14,812 INFO Configuration:879 - processing collection mappings
11:53:14,812 INFO Configuration:888 - processing association property references
11:53:14,812 INFO Configuration:917 - processing foreign key constraints
11:53:15,124 INFO C3P0ConnectionProvider:50 - C3P0 using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://monHote/maBase
11:53:15,124 INFO C3P0ConnectionProvider:51 - Connection properties: {user=monLogin, password=monMotDePasse}
11:53:15,140 INFO C3P0ConnectionProvider:54 - autocommit mode: false
Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@3ae941 [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@1fe88d [ acquireIncrement -> 1, autoCommitOnClose -> false, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, idleConnectionTestPeriod -> 0, initialPoolSize -> 2, maxIdleTime -> 5000, maxPoolSize -> 2, maxStatements -> 100, minPoolSize -> 2, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@1a7ddcf [ description -> null, driverClass -> null, factoryClassLocation -> null, jdbcUrl -> jdbc:mysql://dev05/iepargne, properties -> {user=integrance, password=integrance} ] , propertyCycle -> 300, testConnectionOnCheckout -> false ] , factoryClassLocation -> null, numHelperThreads -> 3 ]
11:53:15,968 INFO SettingsFactory:77 - RDBMS: MySQL, version: 4.1.12a-nt
11:53:15,968 INFO SettingsFactory:78 - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-3.0.16-ga ( $Date: 2004/09/30 07:35:03 $, $Revision: 1.27.2.44 $ )
11:53:15,999 INFO Dialect:92 - Using dialect: org.hibernate.dialect.MySQLDialect
11:53:15,999 INFO TransactionFactoryFactory:34 - Transaction strategy: org.hibernate.transaction.JDBCTransactionFactory
11:53:16,015 INFO TransactionManagerLookupFactory:33 - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
11:53:16,015 INFO SettingsFactory:125 - Automatic flush during beforeCompletion(): disabled
11:53:16,015 INFO SettingsFactory:129 - Automatic session close at end of transaction: disabled
11:53:16,015 INFO SettingsFactory:136 - JDBC batch size: 15
11:53:16,015 INFO SettingsFactory:139 - JDBC batch updates for versioned data: disabled
11:53:16,015 INFO SettingsFactory:144 - Scrollable result sets: enabled
11:53:16,015 INFO SettingsFactory:152 - JDBC3 getGeneratedKeys(): enabled
11:53:16,015 INFO SettingsFactory:160 - Connection release mode: null
11:53:16,031 INFO SettingsFactory:184 - Maximum outer join fetch depth: 1
11:53:16,031 INFO SettingsFactory:187 - Default batch fetch size: 1
11:53:16,031 INFO SettingsFactory:191 - Generate SQL with comments: disabled
11:53:16,031 INFO SettingsFactory:195 - Order SQL updates by primary key: disabled
11:53:16,031 INFO SettingsFactory:334 - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
11:53:16,031 INFO ASTQueryTranslatorFactory:21 - Using ASTQueryTranslatorFactory
11:53:16,031 INFO SettingsFactory:203 - Query language substitutions: {}
11:53:16,031 INFO SettingsFactory:209 - Second-level cache: enabled
11:53:16,031 INFO SettingsFactory:213 - Query cache: disabled
11:53:16,031 INFO SettingsFactory:321 - Cache provider: org.hibernate.cache.EhCacheProvider
11:53:16,046 INFO SettingsFactory:228 - Optimize cache for minimal puts: disabled
11:53:16,046 INFO SettingsFactory:233 - Cache region prefix: hibernate.test
11:53:16,046 INFO SettingsFactory:237 - Structured second-level cache entries: disabled
11:53:16,046 INFO SettingsFactory:261 - Statistics: disabled
11:53:16,046 INFO SettingsFactory:265 - Deleted entity synthetic identifier rollback: disabled
11:53:16,046 INFO SettingsFactory:279 - Default entity-mode: pojo
11:53:16,093 INFO SessionFactoryImpl:152 - building session factory
11:53:16,109 WARN Configurator:125 - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/F:/workspace/ModuleTechniqueIntegrance/webapp/WEB-INF/lib/ehcache-0.9.jar!/ehcache-failsafe.xml
11:53:17,312 INFO SessionFactoryObjectFactory:86 - Factory name: fr.integrance.hibernate.HibernateSessionFactory
11:53:17,312 INFO NamingHelper:26 - JNDI InitialContext properties:{}
11:53:17,328 WARN SessionFactoryObjectFactory:98 - Could not bind factory to JNDI
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getNameParser(Unknown Source)
at org.hibernate.util.NamingHelper.bind(NamingHelper.java:52)
at org.hibernate.impl.SessionFactoryObjectFactory.addInstance(SessionFactoryObjectFactory.java:90)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:260)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1005)
at fr.integrance.hibernate._BaseRootDAO.initialize(_BaseRootDAO.java:55)
at fr.integrance.hibernate._BaseRootDAO.initialize(_BaseRootDAO.java:42)
at fr.integrance.hibernate._BaseRootDAO.initialize(_BaseRootDAO.java:33)
at test.TestHibernate.testGetGerantWithID(TestHibernate.java:34)
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 junit.framework.TestCase.runTest(TestCase.java:154)
at junit.framework.TestCase.runBare(TestCase.java:127)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:118)
at junit.framework.TestSuite.runTest(TestSuite.java:208)
at junit.framework.TestSuite.run(TestSuite.java:203)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:474)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:342)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:194)
11:53:17,328 INFO SessionFactoryImpl:379 - Checking 1 named queries
11:53:17,640 DEBUG SQL:324 - select gerants0_.SERIAL_GERANT as SERIAL1_0_, gerants0_.DAT_DEB as DAT2_1_0_, gerants0_.DAT_FIN as DAT3_1_0_, gerants0_.UID_CRE as UID4_1_0_, gerants0_.DAT_CRE as DAT5_1_0_, gerants0_.UID_MAJ as UID6_1_0_, gerants0_.DAT_MAJ as DAT7_1_0_, gerants0_.LOGIN_ITUTELLE as LOGIN8_1_0_, gerants0_.PWD_ITUTELLE as PWD9_1_0_, gerants0_.SERIAL_SUP as SERIAL10_1_0_ from gerants gerants0_ where gerants0_.SERIAL_GERANT=?
Note : l'exception "javax.naming.NoInitialContextException" est normale car j'utilise un test JUnit qui n'a pas de contexte comme pourrait avoir une application web. Lorsque je lance le même code dans Tomcat cette exception disparaît mais j'ai toujours besoin de faire appel à la méthode "initialize()".