带注释的实体管理器空指向异常 [英] annotated entity manager null pointed exception

查看:29
本文介绍了带注释的实体管理器空指向异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JPA 做一个小项目.我需要插入员工对象.为此,当我使用带注释的实体管理器时,我收到了 NullPointer 异常.但是当我使用 Normal EntityManager 而不使用注释时,它工作正常.我是否需要在persistence.xml 之外的其他地方进行配置才能正常工作?

I am doing a small project using JPA. I need to insert the employee object. For that when I use the annotated entity manager I got the NullPointer exception. But when I use the Normal EntityManager without using the annotation it is working fine. Do I need to configure somewhere else other than persistence.xml to work this examle fine?

请看下面的代码.

public class EmployeeDao implements IEmployeeDao{       

     @PersistenceContext(unitName = "timesheet")
    private EntityManager entityManager ;

    @Override
    public boolean createEmployee(IEmployee employee) { 

        this.entityManager.persist(employee);       

        return true;
    }
}

持久性.xml

<?xml version="1.0" encoding="UTF-8" ?>
<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"
    version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
    <persistence-unit name="timesheet" transaction-type="RESOURCE_LOCAL">       
        <class>com.timesheet.model.Employee</class>     
        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url"
                value="jdbc:mysql://localhost:3306/timesheet" />
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password" value="" />

            <!-- EclipseLink should create the database schema automatically -->
            <property name="eclipselink.ddl-generation" value="create-tables" />
            <property name="eclipselink.ddl-generation.output-mode"
                value="database" />
        </properties>

    </persistence-unit>
</persistence>

推荐答案

资源注入(在您的情况下通过使用 @PersistenceContext)仅适用于容器管理的类(如 EJB 和 Servlet).例如在 Java EE 规范 v6, EE5.2.5 中详细解释了这一点.

Injection of resources (in your case via use of @PersistenceContext) works only in container managed classes (like EJBs and Servlets). This explained with more details for example in Java EE specification v6, EE5.2.5.

你可以做什么:

  • 修改你的类,使其成为托管类
  • 将资源注入移动到托管类并将其传递给员工道,
  • 像以前一样使用 JNDI 查找

这篇关于带注释的实体管理器空指向异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆