Glassfish无法在模块中定位javax.persistence.Persistence

时间:2014-06-02 16:33:56

标签: maven jpa glassfish classloader

我遇到与here相同的问题。我可以毫无错误地部署我的应用程序但是当我尝试查看索引页面时,我得到了一个错误,其原因如下:

[#|2014-06-02T16:53:37.524+0100|WARNING|glassfish3.1.2|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=18;_ThreadName=Thread-2;|StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() for servlet Faces Servlet threw exception
java.lang.ClassNotFoundException: javax.persistence.Persistence
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at sun.misc.Launcher$ExtClassLoader.findClass(Launcher.java:229)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
        at my.database.manager.PersistenceStoreManagerImpl.init(PersistenceStoreManagerImpl.java:57)
        at my.database.manager.PersistenceStoreManagerImpl.getInstance(PersistenceStoreManagerImpl.java:76)
        at my.database.manager.PersistenceCRUDManagerImpl.<init>(PersistenceCRUDManagerImpl.java:49)
        at my.database.model.Serviceprovider.<clinit>(Serviceprovider.java:40)
        at my.server.web.contoller.ServiceProviderController.findAll(ServiceProviderController.java:205)
        at my.server.web.contoller.ServiceProviderController.init(ServiceProviderController.java:62)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.jboss.weld.util.reflection.SecureReflections$13.work(SecureReflections.java:267)
        at org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:52)
        at org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInvocation(SecureReflectionAccess.java:137)
        at org.jboss.weld.util.reflection.SecureReflections.invoke(SecureReflections.java:263)
        at org.jboss.weld.introspector.jlr.WeldMethodImpl.invoke(WeldMethodImpl.java:174)
        at org.jboss.weld.bean.AbstractClassBean.defaultPostConstruct(AbstractClassBean.java:398)
        at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget.postConstruct(ManagedBean.java:174)
        at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:294)
        at org.jboss.weld.context.AbstractContext.get(AbstractContext.java:107)
        at org.jboss.weld.bean.proxy.ContextBeanInstance.getInstance(ContextBeanInstance.java:90)
        at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:104)
        at my.server.web.contoller.ServiceProviderController$Proxy$_$$_WeldClientProxy.showViewDataTable(ServiceProviderController$Proxy$_$$_WeldClientProxy.java)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at javax.el.BeanELResolver.invokeMethod(BeanELResolver.java:779)
        at javax.el.BeanELResolver.invoke(BeanELResolver.java:528)
        at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:257)
        at com.sun.el.parser.AstValue.getValue(AstValue.java:134)
        at com.sun.el.parser.AstValue.getValue(AstValue.java:183)
        at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:224)
        at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
        at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
        at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
        at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
        at javax.faces.component.UIOutput.getValue(UIOutput.java:169)
        at com.sun.faces.renderkit.html_basic.OutputLinkRenderer.getValue(OutputLinkRenderer.java:182)
        at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355)
        at com.sun.faces.renderkit.html_basic.OutputLinkRenderer.renderAsActive(OutputLinkRenderer.java:191)
        at com.sun.faces.renderkit.html_basic.OutputLinkRenderer.encodeBegin(OutputLinkRenderer.java:107)
        at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:820)
        at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1755)
        at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
        at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
        at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
        at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
        at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
        at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
        at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
        at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
        at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
        at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
        at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
        at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
        at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
        at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
        at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
        at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
        at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
        at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
        at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
        at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
        at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
        at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
        at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
        at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
        at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
        at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
        at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
        at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
        at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
        at java.lang.Thread.run(Thread.java:662)

my.database。*和my.server。*是我自己的类,构成了我正在处理的应用程序。有关完整说明,请参阅here,但我认为此问题并非必要。

user1766169's question中,解决方案是将持久性库的范围从provided更改为runtime,因为该库在执行环境中不可用。

然而,我并非如此,因为该库在Glassfish [as-install]/modules/目录中可用。这是asadmin list-modules命令的输出:

  

asadmin> list-modules
  List Of Modules
  .
  .
  .
  Module : javax.persistence:2.0.4.v201112200901
  .
  .
  .
  Command list-modules executed successfully.

所以我假设Glassfish知道持久性模块。我已经检查过javax.persistence.jar存档,javax.persistence.Persistence类在库中。

您是否需要做一些特别的事情来表明Glassfish在其模块目录中使用模块?

更新1 03-06-2014 此问题会间歇性地出现,如果未出现此问题,我会收到以下错误:java.lang.NoClassDefFoundError: Could not initialize class my.database.model.Serviceprovider

更新2 03-06-2014 我认为java.lang.NoClassDefFoundError以有意义的方式相关,但它似乎是因无法找到java.lang.NoClassDefFoundError而导致的次要错误。此外,将[as-install]/modules/目录中的库添加到[as-install]/domains/MyDomain/lib/ext/似乎可以使持久性库可以定位&#39;但是在尝试查找[as-install]/modules/目录中的库中存在的类时会导致进一步的错误。我在底部包含了我的Glassfish配置选项。

MyServer web.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>my-server</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
  <context-param>
    <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
  </context-param>
  <context-param>
    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
    <param-value>resources.application</param-value>
  </context-param>
  <context-param>
    <param-name>javax.faces.FACELETS_LIBRARIES</param-name>
    <param-value>/WEB-INF/balusc.taglib.xml</param-value>
  </context-param>
  <context-param>
    <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
    <param-value>true</param-value>
  </context-param>
  <filter>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
  </filter-mapping>
  <context-param>
    <param-name>javax.faces.PARTIAL_STATE_SAVING</param-name>
    <param-value>false</param-value>
  </context-param>
  <listener>
    <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
  </listener>
</web-app>

MyServer persistence.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="my_persistence_unit" transaction-type="JTA">
      <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <jta-data-source>my_persistence_unit</jta-data-source>
        <class>my.database.model.Table1</class>
        .
        .
        .
        <class>my.database.model.TableN</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>

         <properties>
           <property name="eclipselink.logging.level" value="FINE"/>
           <property name="validation-mode" value="NONE"/>
           <property name="eclipselink.cache.shared.default" value="false"/>
           <property name="eclipselink.ddl-generation" value="create-tables" />
           <property name="openjpa.DynamicEnhancementAgent" value="false"/>
           <property name="openjpa.RuntimeUnenhancedClasses" value="unsupported" />
         </properties>

    </persistence-unit>
</persistence>

MyServer POM文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>my.webapp</groupId>
    <artifactId>my-server</artifactId>
    <version>0.1.0-SNAPSHOT</version>
    <name>My Server</name>
    <parent>
        <groupId>my.webapp</groupId>
        <artifactId>my-parent-pom</artifactId>
        <version>1.5</version>
    </parent>
    <organization>
        <name>Example</name>
        <url>http://www.example.com</url>
    </organization>
    <repositories>
        <repository>
            <id>eclipselink</id>
            <url>http://www.eclipse.org/downloads/download.php?r=1&amp;nf=1&amp;file=/rt/eclipselink/maven.repo/</url>
        </repository>
    </repositories>
    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>eclipselink</groupId>
            <artifactId>eclipselink</artifactId>
            <version>2.3.0</version>
        </dependency>

        <dependency>
            <groupId>utilities</groupId>
            <artifactId>utilities</artifactId>
            <version>0.1.0</version>
        </dependency>

        <dependency>
            <groupId>javax.enterprise</groupId>
            <artifactId>cdi-api</artifactId>
            <version>1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>my.webapp</groupId>
            <artifactId>my-database</artifactId>
            <version>0.1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>3.4.1</version>
        </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-io</artifactId>
        <version>1.3.2</version>
    </dependency>
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.2.1</version>
    </dependency>
    </dependencies>

    <packaging>war</packaging>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <!-- <configuration> section added to pick up the WEB-INF/web.xml inside
                    WebContent -->
                <configuration>
                    <webResources>
                        <resource>
                            <directory>WebContent</directory>
                        </resource>
                    </webResources>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <scm>
        <connection>scm:svn:https://svn.server/location/in/repo/my_server</connection>
        <developerConnection>scm:svn:https://svn.server/location/in/repo/my_server/trunk</developerConnection>
    </scm>
</project>

MyDatabase persistence.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="my_persistence_unit" transaction-type="JTA">
      <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <jta-data-source>my_persistence_unit</jta-data-source>
        <class>my.database.model.Table1</class>
        .
        .
        .
        <class>my.database.model.TableN</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>

         <properties>
           <property name="eclipselink.logging.level" value="FINE"/>
           <property name="validation-mode" value="NONE"/>
           <property name="eclipselink.cache.shared.default" value="false"/>
           <property name="eclipselink.ddl-generation" value="create-tables" />
           <property name="openjpa.DynamicEnhancementAgent" value="false"/>
           <property name="openjpa.RuntimeUnenhancedClasses" value="unsupported" />
         </properties>

    </persistence-unit>
</persistence>

MyDatabase POM文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <artifactId>my-database</artifactId>
  <version>0.1.0-SNAPSHOT</version>
  <parent>
    <groupId>my.webapp</groupId>
    <artifactId>my-parent-pom</artifactId>
    <version>1.5</version>
  </parent>
  <dependencies>
    <dependency>
      <groupId>eclipselink</groupId>
      <artifactId>eclipselink</artifactId>
      <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.10</version>
        <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mindrot</groupId>
      <artifactId>bcrypt</artifactId>
      <version>0.2.0</version>
    </dependency>
    <dependency>
        <groupId>my.webapp</groupId>
        <artifactId>my-interfaces</artifactId>
        <version>0.1.0-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.apache.geronimo.specs</groupId>
        <artifactId>geronimo-jpa_3.0_spec</artifactId>
        <version>1.1.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.0.5</version>
        <scope>test</scope>
    </dependency>
  </dependencies>
  <scm>
    <connection>scm:svn:https://svn.server/location/in/repo/my_database</connection>
    <developerConnection>scm:svn:https://svn.server/location/in/repo/my_database/trunk/</developerConnection>
  </scm>
  <groupId>my.webapp</groupId>
</project>

my.database.PersistenceStoreManagerImpl class

/**
 *
 */
package my.database.manager;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import my.database.interfaces.PersistenceStoreManager;

/**
 * This class is responsible for providing the entity manager that will manage
 * the entity instances and their life cycles.This class should implement the
 * PersistenceStoreManager interfaces
 *
 */
public class PersistenceStoreManagerImpl implements PersistenceStoreManager
{
    /**
     * This is the default database name which is used for accessing the database.
     * This must match the persistence.xml value
     */
    private static final String DATABASE_NAME = "my_persistence_unit";

    private static EntityManagerFactory EMF = null;
    /**
     * This variable is associated with the persistence context. This variable
     * is used to create and remove persistent entity instances, to find
     * entities by their primary key, and to query over entities.
     */
    private EntityManager em;
    /**
     * This is the instance of the class and should always be fetched by
     * getInstance() method
     */
    private static PersistenceStoreManagerImpl instance;

    /**
     * This is the default constructor of the class, this is made private so
     * that the instance can be created through getInstance()
     */
    private PersistenceStoreManagerImpl() {

    }

    /**
     * Creates the EntityManagerFactory from the supplied database name.
     * This must be done before getInstance() is called.
     *
     * @param databaseName
     */
    public static void init(String databaseName)
    {
        EMF = Persistence.createEntityManagerFactory(databaseName);
        System.out.println("PersistenceStoreManager initialised to use database " + databaseName);
    }


    /*
     * Returns the singleton instance.
     * If the class has not yet been initialised, it will be initialised with the default database name
     *
     * @returns the singleton instance or null if it has not been initialised.
     */

    public static PersistenceStoreManager getInstance()
    {
        if (null == instance)
        {
            // If the database name has not been set, use the default one
            if (EMF == null)
            {
                init(DATABASE_NAME);
            }
            instance = new PersistenceStoreManagerImpl();

        }
        return instance;
    }

    /*
     * (non-Javadoc)
     *
     * @see my.interfaces.PersistenceStoreManager#setConnection()
     */
    @Override
    public void setConnection() {
        this.em = EMF.createEntityManager();
    }

    /*
     * (non-Javadoc)
     *
     * @see my.interfaces.PersistenceStoreManager#
     * getEntityManagerForTransaction()
     */
    @Override
    public EntityManager getEntityManager() {
        setConnection();
        if (!em.getTransaction().isActive()) {
            em.getTransaction().begin();
        }
        return em;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * my.interfaces.PersistenceStoreManager#commitAndCloseConnection
     * ()
     */
    @Override
    public void commitAndCloseConnection() {
        em.getTransaction().commit();
        em.clear();
        em.close();
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * my.interfaces.PersistenceStoreManager#closeConnection()
     */
    @Override
    public void closeConnection() {
        em.close();

    }

}

my.interfaces.PersistenceStoreManager接口类

/*
 * 
 */
package my.interfaces;

import javax.persistence.EntityManager;

/**
 * This class is responsible for managing the persistence store.
 *
 * 
 */
public interface PersistenceStoreManager {
    /**
     * This method is called to establish the connection with the persistence
     * storage
     */
    public void setConnection();

    /**
     * This method gives the instance of the entity manager that would
     * fetch/persist(add new data)/merge(update existing data). This method
     * should always return an active transaction or begin a new transaction
     *
     * @return entity manager
     */
    public EntityManager getEntityManager();

    /**
     * This method is called to close the existing connection.
     */
    public void closeConnection();

    /**
     * This method is called to commit the transaction , clear the persistence
     * context and then close the existing connection.
     */
    public void commitAndCloseConnection();


}

使用以下配置启动My Glassfish服务器:

INFO: JVM invocation command line:
  -XX:+UnlockDiagnosticVMOptions
  -XX:PermSize=64m
  -XX:MaxPermSize=192m
  -XX:NewRatio=2
  -Xmx512m
  -client
  -javaagent:/opt/glassfish3/glassfish/lib/monitor/flashlight-agent.jar
  -Dosgi.shell.telnet.maxconn=1
  -Dfelix.fileinstall.disableConfigSave=false
  -Djdbc.drivers=org.apache.derby.jdbc.ClientDriver
  -Dfelix.fileinstall.dir=/opt/glassfish3/glassfish/modules/autostart/
  -Djavax.net.ssl.keyStore=/opt/glassfish3/glassfish/domains/MyDomain/config/keystore.jks
  -Dosgi.shell.telnet.port=6666
  -Djava.security.policy=/opt/glassfish3/glassfish/domains/MyDomain/config/server.policy
  -Djava.awt.headless=true
  -Dfelix.fileinstall.log.level=2
  -Dfelix.fileinstall.poll=5000
  -Dcom.sun.aas.instanceRoot=/opt/glassfish3/glassfish/domains/MyDomain
  -Dosgi.shell.telnet.ip=127.0.0.1
  -Dcom.sun.enterprise.config.config_environment_factory_class=com.sun.enterprise.config.serverbeans.AppserverConfigEnvironmentFactory
  -Djava.endorsed.dirs=/opt/glassfish3/glassfish/modules/endorsed:/opt/glassfish3/glassfish/lib/endorsed
  -Dcom.sun.aas.installRoot=/opt/glassfish3/glassfish
  -Dfelix.fileinstall.bundles.startTransient=true
  -Djava.ext.dirs=/opt/java/lib/ext:/opt/java/jre/lib/ext:/opt/glassfish3/glassfish/domains/MyDomain/lib/ext
  -Dfelix.fileinstall.bundles.new.start=true
  -Djavax.net.ssl.trustStore=/opt/glassfish3/glassfish/domains/MyDomain/config/cacerts.jks
  -Dcom.sun.enterprise.security.httpsOutboundKeyAlias=s1as
  -Djava.security.auth.login.config=/opt/glassfish3/glassfish/domains/MyDomain/config/login.conf
  -DANTLR_USE_DIRECT_CLASS_LOADING=true
  -Dgosh.args=--nointeractive

1 个答案:

答案 0 :(得分:0)

尽管您提出了初步问题,但在使用PersistenceStoreManagerImpl时,您不需要您不应该执行所有这些操作,例如在JTA中手动管理交易(如persistence.xml所示)。

它应该与此示例类似:

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class FileDAO {

    @PersistenceContext
    private EntityManager em;

    public void store(File file) {
        em.persist(file);
    }
}

这几乎就是你所需要的。您可以通过使用@EJB注释注入它来在另一个类中使用它。

这并不明确需要类javax.persistence.Persistence,而是来自同一个包的其他类:)

如果您指定了交易类型JTA并且您想要手动管理EntityManager,那么有些事情需要考虑,在this question中可以很好地解释。

在我看来,如果你使用能够提供JTA(你可能有)的应用服务器和JDBC驱动程序,JTA应该是首选的事务类型。正如您在示例中看到的那样,它会使许多代码过时。它也不易出错。