Я запускаю проект с использованием ICEFaces и Hibernate на сервере JBoss AplicationServer, и теперь я не могу заставить Hibernate работать.
Проблема в том, что мои классы DAO не могут получить SassionFacade.
Я думаю, что Hibernate не создает его из-за тех же конфликтов с JNDI
Что я сделал до сих пор:
настройка моей базы данных с MySQL. Я использовал этот урок: https://community.jboss.org/wiki/DataSourceConfigurationInAS7
(Я установил драйвер JDBC в качестве модели), не уверен, что он работает, потому что при запуске сервера он выглядит так, как будто он загружает другой драйвер
18:30:26,980 INFO [org.jboss.as.connector.subsystems.datasources] (ServerService Thread Pool -- 26) JBAS010403: Deploying JDBC-compliant driver class org.h2.Driver (version 1.3)
Чем я в значительной степени воспользовался первой стороной этого урока:
http://www.packtpub.com/article/developing-applications-with-jboss-and-hibernate-1
и похоже, что это сработало, я вижу свою базу данных и таблицы, но флаг Session Factory пуст и показывает мне это предупреждение:
2012-01-26 18:36:25,177 WARN Worker-14 org.hibernate.impl.SessionFactoryObjectFactory - Could not bind factory to JNDIjavax.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:75)
at org.hibernate.impl.SessionFactoryObjectFactory.addInstance(SessionFactoryObjectFactory.java:113)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:378)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1385)
at org.hibernate.console.ConsoleConfiguration$4.execute(ConsoleConfiguration.java:268)
at org.hibernate.console.execution.DefaultExecutionContext.execute(DefaultExecutionContext.java:63)
at org.hibernate.console.ConsoleConfiguration.execute(ConsoleConfiguration.java:107)
at org.hibernate.console.ConsoleConfiguration.buildSessionFactory(ConsoleConfiguration.java:263)
at org.hibernate.eclipse.console.workbench.LazySessionFactoryAdapter.getChildren(LazySessionFactoryAdapter.java:43)
at org.hibernate.eclipse.console.workbench.BasicWorkbenchAdapter.getChildren(BasicWorkbenchAdapter.java:100)
at org.hibernate.eclipse.console.workbench.BasicWorkbenchAdapter.fetchDeferredChildren(BasicWorkbenchAdapter.java:106)
at org.eclipse.ui.progress.DeferredTreeContentManager$1.run(DeferredTreeContentManager.java:235)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
Я помню, что в тот же момент у меня были те же Session Factorys, но бот не помнит, что я изменил, что они diassapeard.
Поскольку это всего лишь предупреждение, я продолжал учебник и успешно сгенерировал классы для своей таблицы и DAO, чем когда я писал небольшую тестовую программу, использовал один из DAO и получил следующую ошибку:
18:42:44,232 SCHWERWIEGEND [db.fassaden.hibernate.PlattenHome] (http--127.0.0.1-8080-3) Could not locate SessionFactory in JNDI: javax.naming.NameNotFoundException: SessionFactory -- service jboss.naming.context.java.SessionFactory
at org.jboss.as.naming.ServiceBasedNamingStore.lookup(ServiceBasedNamingStore.java:92)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:177)
at org.jboss.as.naming.InitialContext.lookup(InitialContext.java:87)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:213)
at javax.naming.InitialContext.lookup(Unknown Source) [:1.6.0_17]
at db.fassaden.hibernate.PlattenHome.getSessionFactory(PlattenHome.java:26) [classes:]
at db.fassaden.hibernate.PlattenHome.<init>(PlattenHome.java:22) [classes:]
at fassadenkalkulation.kalkulation.testhibernate(kalkulation.java:21) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [:1.6.0_17]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) [:1.6.0_17]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) [:1.6.0_17]
at java.lang.reflect.Method.invoke(Unknown Source) [:1.6.0_17]
at org.apache.el.parser.AstValue.invoke(AstValue.java:262) [jbossweb-7.0.7.Final.jar:]
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278) [jbossweb-7.0.7.Final.jar:]
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105) [jsf-impl-2.1.5-jbossorg-1.jar:2.1.5-SNAPSHOT]
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:148) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:769) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
at javax.faces.component.UICommand.broadcast(UICommand.java:300) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) [jsf-impl-2.1.5-jbossorg-1.jar:2.1.5-SNAPSHOT]
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.1.5-jbossorg-1.jar:2.1.5-SNAPSHOT]
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) [jsf-impl-2.1.5-jbossorg-1.jar:2.1.5-SNAPSHOT]
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.7.Final.jar:]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.7.Final.jar:]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.7.Final.jar:]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.7.Final.jar:]
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:151) [jboss-as-web-7.1.0.CR1b.jar:7.1.0.CR1b]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.7.Final.jar:]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.7.Final.jar:]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.7.Final.jar:]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:362) [jbossweb-7.0.7.Final.jar:]
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:897) [jbossweb-7.0.7.Final.jar:]
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:626) [jbossweb-7.0.7.Final.jar:]
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:2033) [jbossweb-7.0.7.Final.jar:]
at java.lang.Thread.run(Unknown Source) [:1.6.0_17]
18:42:44,237 SCHWERWIEGEND [javax.faces.event] (http--127.0.0.1-8080-3) Beim Aufrufen des Aktionszielgeräts 'java.lang.IllegalStateException' für Komponente '#{kalkulation.testhibernate}' wurde '_t8' erhalten. ...
Это серверы standalone.xml
<datasources> <datasource jndi-name="java:jboss/datasources/MySqlDS" pool-name="MySqlDS">
<connection-url>
jdbc:mysql://localhost:3306/fassaden
</connection-url>
<driver>
com.mysql
</driver>
<transaction-isolation>
TRANSACTION_READ_COMMITTED
</transaction-isolation>
<pool>
<min-pool-size>
10
</min-pool-size>
<max-pool-size>
100
</max-pool-size>
<prefill>
true
</prefill>
</pool>
<security>
<user-name>
root
</user-name>
<password>
1taste
</password>
</security>
<statement>
<prepared-statement-cache-size>
32
</prepared-statement-cache-size>
<share-prepared-statements>
true
</share-prepared-statements>
</statement>
</datasource>
<datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">
<connection-url>
jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
</connection-url>
<driver>
h2
</driver>
<security>
<user-name>
sa
</user-name>
<password>
sa
</password>
</security>
</datasource>
<drivers>
<driver name="com.mysql" module="com.mysql">
<xa-datasource-class>
com.mysql.jdbc.jdbc2.optional.MysqlXADataSource
</xa-datasource-class>
</driver>
<driver name="h2" module="com.h2database.h2">
<xa-datasource-class>
org.h2.jdbcx.JdbcDataSource
</xa-datasource-class>
</driver>
</drivers>
</datasources>
Моя конфигурация гибернации (hibernate.cfg.xml)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="SessionFactory">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">1taste</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/fassaden</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
</session-factory>
</hibernate-configuration>
Сгенерированный из Hibernate DAO (PlattenHome.java)
package db.fassaden.hibernate;
// Generated 26.01.2012 15:18:18 by Hibernate Tools 3.4.0.CR1
import java.util.List;
import javax.naming.InitialContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
/**
* Home object for domain model class Platten.
* @see db.fassaden.hibernate.Platten
* @author Hibernate Tools
*/
public class PlattenHome {
private static final Log log = LogFactory.getLog(PlattenHome.class);
private final SessionFactory sessionFactory = getSessionFactory();
protected SessionFactory getSessionFactory() {
try {
return (SessionFactory) new InitialContext().lookup("SessionFactory");
}
catch (Exception e) {
log.error("Could not locate SessionFactory in JNDI", e);
throw new IllegalStateException("Could not locate SessionFactory in JNDI");
}
}
...
public Platten findById( java.lang.Integer id) {
log.debug("getting Platten instance with id: " + id);
try {
Platten instance = (Platten) sessionFactory.getCurrentSession()
.get("db.fassaden.hibernate.Platten", id);
if (instance==null) {
log.debug("get successful, no instance found");
}
else {
log.debug("get successful, instance found");
}
return instance;
}
catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
и как я его использую:
public void testhibernate(ActionEvent e){
PlattenHome pdao = new PlattenHome();
Platten platte = new Platten();
platte = pdao.findById(1);
this.setName(platte.getMaterial());
System.out.println("test");
System.out.println(platte.getMaterial());
}
Я только что заметил, что если я перекомпилирую конфигурацию гибернации сейчас, после запуска сервера, это выдаст мне другое предупреждение
2012-01-26 18:48:55,359 WARN main org.hibernate.impl.SessionFactoryObjectFactory - Could not unbind factory from 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.unbind(Unknown Source)
at org.hibernate.impl.SessionFactoryObjectFactory.removeInstance(SessionFactoryObjectFactory.java:139)
at org.hibernate.impl.SessionFactoryImpl.close(SessionFactoryImpl.java:981)
at org.hibernate.console.ConsoleConfiguration.closeSessionFactory(ConsoleConfiguration.java:411)
at org.hibernate.console.ConsoleConfiguration.reset(ConsoleConfiguration.java:130)
at org.hibernate.eclipse.console.views.ReloadConfigurationAction.doRun(ReloadConfigurationAction.java:34)
at org.hibernate.eclipse.console.actions.ConsoleConfigurationBasedAction.run(ConsoleConfigurationBasedAction.java:65)
at org.eclipse.ui.actions.BaseSelectionListenerAction.runWithEvent(BaseSelectionListenerAction.java:168)
at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:584)
at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:501)
at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:411)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4165)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3754)
at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2696)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2660)
at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2494)
at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:674)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:667)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:123)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:344)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
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 org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:622)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:577)
at org.eclipse.equinox.launcher.Main.run(Main.java:1410)
at org.eclipse.equinox.launcher.Main.main(Main.java:1386)