在EntityManager关闭之前执行任务

时间:2014-07-06 15:28:51

标签: java-ee jpa glassfish eclipselink entitymanager

我想在关闭EntityManager之前执行任务(例如关闭AS或取消应用程序)并寻找Hook或Listener或类似的东西。

实际问题: 我想用我的应用程序在数据库中保存很多微小的数据。为了减轻数据库的负担,我将数据缓存在List中,并希望以给定的间隔保存所有数据。

到目前为止这种方法很有效但是如果AS正在关闭,数据将会丢失。这就是我想在EntityManager关闭之前保存数据的原因。

到目前为止我尝试了什么: 我试图在销毁bean之前使用@PreDestroy注释来保存数据。不幸的是,EntityManager的使用不起作用,正如我稍后读到的那样,在PreDestroy方法中不允许使用。

@Singleton
@Startup
@DependsOn(value = "StatisticRepository")
public class StatisticService {
    private static final Logger LOG = Logger.getLogger(StatisticService.class.getName());

    @EJB
    private StatisticRepository repository;
    private List<Statistic> stats = new ArrayList<>();

    @PreDestroy
    public void destroy() {
        LOG.log(Level.INFO, "Saving before destroying Service.");
        for (Statistic stat : stats) {
            // ---> EntityManager in Repository already destroyed
            repository.create(stat);
        }
        stats.clear();
    }
...
}

@Singleton
@Startup
public class StatisticRepository extends BaseRepository<Statistic>{
    public StatisticRepository() {
        super(Statistic.class);
    }

    @PersistenceContext(unitName = PERSISTENCE_UNIT_NAME)
    EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }
    ...
}

@MappedSuperclass
public abstract class BaseRepository<T extends Serializable> {

    protected abstract EntityManager getEntityManager();
    private final Class<T> entityClass;

    public BaseRepository(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    public T create(T entity) {
        getEntityManager().persist(entity);
        getEntityManager().flush();
        return this.edit(entity);
    }
    ...
}

我在

上得到了这个例外
Information:   Saving Statistics before destroying Service.
Warnung:   RAR5114 : Error allocating connection : [{ PoolInfo : (name=java:app/pool), (applicationName=AppName) }: Es ist kein Poolmetadaten-Objekt mit dem Pool { PoolInfo : (name=java:app/pool), (applicationName=AppName) } verknüpft. Stellen Sie die Anwendung erneut bereit. ]
Warnung:   Local Exception Stack: 
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: { PoolInfo : (name=java:app/pool), (applicationName=AppName) }: Es ist kein Poolmetadaten-Objekt mit dem Pool { PoolInfo : (name=java:app/pool), (applicationName=AppName) } verknüpft. Stellen Sie die Anwendung erneut bereit. 
Error Code: 0
...

似乎池(应用程序范围)已经取消部署。

完整堆栈跟踪:
here

我通过glassfish-resources.xml创建我的JNDI资源和连接池。因此,它是应用程序服务器范围的资源。也许这是重现错误的关键?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
  <!-- MySQL -->
  <jdbc-connection-pool allow-non-component-callers="false"
                        associate-with-thread="false"
                        connection-creation-retry-attempts="0"
                        connection-creation-retry-interval-in-seconds="10"
                        connection-leak-reclaim="false"
                        connection-leak-timeout-in-seconds="0"
                        connection-validation-method="auto-commit"
                        datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
                        fail-all-connections="false"
                        idle-timeout-in-seconds="170"
                        is-connection-validation-required="true"
                        is-isolation-level-guaranteed="true"
                        transaction-isolation-level="repeatable-read"
                        lazy-connection-association="false"
                        lazy-connection-enlistment="false"
                        match-connections="false"
                        max-connection-usage-count="0"
                        max-pool-size="100"
                        max-wait-time-in-millis="60000"
                        name="java:app/mysql_app_appPool"
                        non-transactional-connections="false"
                        ping="true"
                        pool-resize-quantity="2"
                        pooling="true"
                        res-type="javax.sql.DataSource"
                        statement-cache-size="0"
                        statement-leak-reclaim="false"
                        statement-leak-timeout-in-seconds="0"
                        statement-timeout-in-seconds="0"
                        steady-pool-size="20"
                        validate-atmost-once-period-in-seconds="0"
                        wrap-jdbc-objects="true">
    <property name="user" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="driverClass" value="com.mysql.jdbc.Driver"/>
  </jdbc-connection-pool>
  <jdbc-resource enabled="true" jndi-name="java:app/jdbc/app" object-type="user" pool-name="java:app/mysql_app_appPool"/>

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <!-- Persistence Unit for MySQL -->
  <persistence-unit name="com.app.web_app-webapp_war_1.0-SNAPSHOTPU" transaction-type="JTA">
    <jta-data-source>java:app/jdbc/app</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="javax.persistence.schema-generation.database.action" value="create"/>
      <property name="javax.persistence.schema-generation.create-source" value="metadata-then-script"/>
      <property name="javax.persistence.schema-generation.drop-source" value="metadata"/>
      <property name="javax.persistence.schema-generation-target" value="database"/>
    </properties>
  </persistence-unit>
</persistence>

问题: 你对这个机制有什么看法? 缓存是否有意义,因为JPA可以自己更好地处理它? 有没有听众或挂钩?

1 个答案:

答案 0 :(得分:1)

eclipselink上有很多缓存选项。看看here

另外,对于现实生活表现,我强烈建议使用Infinspan。看看here

如果您的用例非常简单,那么使用@Singleton注释的@Startup ejb bean应该可以解决问题。像这样:

@Singleton
@Startup
public class StartupShutdownBean {

    @PostConstruct
    private void startup() {
        // your startup code here
    }

    @PreDestroy
    private void shutdown() {
        // your shutdown code here
    }

}

在这个bean上注入EntityManager时不应该有任何问题。最有可能的是,您无法在bean中使用实体管理器,因为事务在您执行&#34;缓存更新之前就已结束了。

编辑:

@PreDestroy调用之前,AS似乎正在删除应用程序配置的资源,因此您应该在asadmin部署或重新部署命令中使用preserveAppScopedResources=true参数,以便在期间保持池的活动状态那些行动。

一些文档here