在 java-ee 批处理作业中注入 EntityManager null

Injected EntityManager null in java-ee batch job

我正在尝试使用注入的实体管理器来保存使用 java-ee 的批处理作业的输出,但是 EntityManager 始终为空。我在 glassfish 上使用 Maven Web 应用程序 运行 并按如下方式安排作业。

@Stateless
public class Scheduler {

    @Schedule(minute = "*/1", hour = "*")
    public void runEveryMinute() {
        JobOperator jobOperator = BatchRuntime.getJobOperator();        
        jobOperator.start("newOrderProcessJob", null);     
    }
}

在我的写作步骤中

@Named
public class OrderWriter extends AbstractItemWriter {

    @PersistenceContext()
    EntityManager em;

    @Override
    public void writeItems(List<Object> list){

        for (Object p : list) {                
            em.merge(p);
        }
    }
}

还有我的persistence.xml

<?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 name="com.mycompany_mavenproject1_war_1.0-SNAPSHOTPU" transaction-type="JTA">
       <jta-data-source>jdbc/directory</jta-data-source>
       <exclude-unlisted-classes>false</exclude-unlisted-classes>
       <properties>
           <property name="javax.persistence.schema-                      generation.database.action" value="create"/>
       </properties>    
   </persistence-unit>
</persistence>

有人知道如何解决这个问题吗?

我记不清具体规则了,但只有特定的一组 类 可以保证扫描并使用该 JPA 注释注入,批处理工件不包含在该列表中。

因此您必须执行其他操作,例如:

EntityManagerFactory emf = Persistence.createEntityManagerFactory("com.mycompany_mavenproject1_war_1.0-SNAPSHOTPU");
 em = emf.createEntityManager();

或者你可以这样做:

@Named
@PersistenceContext(unitName = "com.mycompany_mavenproject1_war_1.0-SNAPSHOTPU", name = "persistence/em")
public class OrderWriter extends AbstractItemWriter {

    EntityManager em;

    @Override
    public void open(Serializable checkpoint) {
        try {
            InitialContext ic = new InitialContext();
            em = (EntityManager) ic.lookup("java:comp/env/persistence/em");
        } catch (NamingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void writeItems(List<Object> list){

        for (Object p : list) {                
            em.merge(p);
        }
    }
}

与 web.xml:

    <persistence-context-ref>
            <persistence-context-ref-name>persistence/em</persistence-context-ref-name>
            <persistence-unit-name>com.mycompany_mavenproject1_war_1.0-SNAPSHOTPU</persistence-unit-name>
    </persistence-context-ref>