我尝试使用Sun Java PetStore演示 在CatalogFacade类中,有以下注释:
@PersistenceUnit(unitName="myPetStorePU")
private EntityManagerFactory emf;
在CatalogFacade Sun的所有方法中都有:
EntityManager em = emf.createEntityManager();
但是在尝试createEntityManager时,我得到emf的空指针异常。但是......如果我在该行上面添加以下行
EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("myPetStorePU");
EntityManager em = emf.createEntityManager();
然后emf成功创建,持久性单元myPetStorePU也成功连接到数据库。所以它看起来像persistence.xml语法和它的位置是正确的。我想理解为什么注释不起作用,因为我认为有理由只使用注释而不是在每个方法中添加createEntityManagerFactory行。
我的src / META-INF / persistence.xml文件如下所示:
<persistence-unit name="myPetStorePU">
<description>Petstore Persistence Unit</description>
<provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>
<class>com.sun.javaee.blueprints.petstore.model.Tag</class>
<class>com.sun.javaee.blueprints.petstore.model.SellerContactInfo</class>
<class>com.sun.javaee.blueprints.petstore.model.Product</class>
<class>com.sun.javaee.blueprints.petstore.model.Item</class>
<class>com.sun.javaee.blueprints.petstore.model.Category</class>
<class>com.sun.javaee.blueprints.petstore.model.Address</class>
<class>com.sun.javaee.blueprints.petstore.model.ZipLocation</class>
<properties>
<property name="toplink.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/>
<property name="toplink.jdbc.url" value="jdbc:oracle:thin:@#############"/>
<property name="toplink.jdbc.user" value="####"/>
<property name="toplink.jdbc.password" value="#####"/>
<property name="toplink.logging.level" value="INFO"/>
</properties>
</persistence-unit>
编辑: CatalogFacade位于petstore.model包中并实现ServletContextListener
<listener>
<listener-class>com.sun.javaee.blueprints.petstore.model.CatalogFacade</listener-class>
</listener>
index.jsp中的Sun具有以下内容:
<%
CatalogFacade cf = (CatalogFacade)config.getServletContext().getAttribute("CatalogFacade");
List<Tag> tags=cf.getTagsInChunk(0, 12);
%>
public List<Tag> getTagsInChunk(int start, int chunkSize) {
//The next line is required since the @PersistenceUnit annotation at the top of this class does not work
EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("myPetStorePU");
EntityManager em = emf.createEntityManager();
System.out.println("Entity manager " + emf);
Query query = em.createQuery("SELECT t FROM Tag t ORDER BY t.refCount DESC, t.tag");
List<Tag> tags = query.setFirstResult(start).setMaxResults(chunkSize).getResultList();
em.close();
return tags;
}
答案 0 :(得分:10)
如果带注释的对象不是由容器(spring / CDI / EJB容器)管理的,则不会向其注入任何内容。
因此,根据您的环境,获取该对象的上下文实例。
如果您未使用上述任何技术(spring / CDI / EJB),则无法使用@PersistenceUnit
和@PersistenceContext
。使用手动方式获取装置。
答案 1 :(得分:0)
由于某些原因,在persistence.xml
<provider>org.hibernate.ejb.HibernatePersistence</provider>
切换到
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
修复了问题