我正在尝试使用注入的实体管理器使用java-ee持久保存批处理作业的输出,但EntityManager始终为null。我正在使用在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>
有没有人知道如何解决这个问题?
答案 0 :(得分:0)
我不完全记住规则,但只保证扫描某些类并使用该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>