基于数据库的Restful Web服务的NullPointerException



我是restful web服务开发的新手。我试图使用Netbeans的模板从数据库(本地mysql)创建一个。我在数据库中有一个名为"工作场所"的表。这是我的WorkplacesFacadeREST.java:

@Stateless
@Path("com.rest.api.workplaces")
public class WorkplacesFacadeREST extends AbstractFacade<Workplaces> {
    @PersistenceContext(unitName = "com.rest_hiring_challenge_war_1.0-SNAPSHOTPU")
    private EntityManager em;
public WorkplacesFacadeREST() {
    super(Workplaces.class);
}
@POST
@Override
@Consumes({"application/xml", "application/json"})
public void create(Workplaces entity) {
    super.create(entity);
}
@PUT
@Path("{id}")
@Consumes({"application/xml", "application/json"})
public void edit(@PathParam("id") Integer id, Workplaces entity) {
    super.edit(entity);
}
@DELETE
@Path("{id}")
public void remove(@PathParam("id") Integer id) {
    super.remove(super.find(id));
}
@GET
@Path("{id}")
@Produces({"application/xml", "application/json"})
public Workplaces find(@PathParam("id") Integer id) {
    return super.find(id);
}
@GET
@Override
@Produces({"application/xml", "application/json"})
public List<Workplaces> findAll() {
    return super.findAll();
}
@GET
@Path("{from}/{to}")
@Produces({"application/xml", "application/json"})
public List<Workplaces> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
    return super.findRange(new int[]{from, to});
}
@GET
@Path("count")
@Produces("text/plain")
public String countREST() {
    return String.valueOf(super.count());
}
@Override
protected EntityManager getEntityManager() {
    return em;
}
}

AbstractFacade.java:

public abstract class AbstractFacade<T> {
    private Class<T> entityClass;
    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }
    protected abstract EntityManager getEntityManager();
    public void create(T entity) {
        getEntityManager().persist(entity);
    }
    public void edit(T entity) {
        getEntityManager().merge(entity);
    }
    public void remove(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }
    public T find(Object id) {
        return getEntityManager().find(entityClass, id);
    }
    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }
    public List<T> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        q.setMaxResults(range[1] - range[0] + 1);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }
    public int count() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
        cq.select(getEntityManager().getCriteriaBuilder().count(rt));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }
}

我的实体类workplace .java:

@Entity
@Table(name = "workplaces")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Workplaces.findAll", query = "SELECT w FROM Workplaces w"),
    @NamedQuery(name = "Workplaces.findBySpId", query = "SELECT w FROM Workplaces w WHERE w.spId = :spId"),
    @NamedQuery(name = "Workplaces.findByWorkers", query = "SELECT w FROM Workplaces w WHERE w.workers = :workers"),
    @NamedQuery(name = "Workplaces.findByLatitude", query = "SELECT w FROM Workplaces w WHERE w.latitude = :latitude"),
    @NamedQuery(name = "Workplaces.findByLongitude", query = "SELECT w FROM Workplaces w WHERE w.longitude = :longitude")})
public class Workplaces implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @NotNull
    @Column(name = "sp_id")
    private Integer spId;
    @Basic(optional = false)
    @NotNull
    @Column(name = "workers")
    private int workers;
    @Basic(optional = false)
    @NotNull
    @Column(name = "latitude")
    private float latitude;
    @Basic(optional = false)
    @NotNull
    @Column(name = "longitude")
    private float longitude;
    public Workplaces() {
    }
    public Workplaces(Integer spId) {
        this.spId = spId;
    }
    public Workplaces(Integer spId, int workers, float latitude, float longitude) {
        this.spId = spId;
        this.workers = workers;
        this.latitude = latitude;
        this.longitude = longitude;
    }
    public Integer getSpId() {
        return spId;
    }
    public void setSpId(Integer spId) {
        this.spId = spId;
    }
    public int getWorkers() {
        return workers;
    }
    public void setWorkers(int workers) {
        this.workers = workers;
    }
    public float getLatitude() {
        return latitude;
    }
    public void setLatitude(float latitude) {
        this.latitude = latitude;
    }
    public float getLongitude() {
        return longitude;
    }
    public void setLongitude(float longitude) {
        this.longitude = longitude;
    }
    @Override
    public int hashCode() {
        int hash = 0;
        hash += (spId != null ? spId.hashCode() : 0);
        return hash;
    }
    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Workplaces)) {
            return false;
        }
        Workplaces other = (Workplaces) object;
        if ((this.spId == null && other.spId != null) || (this.spId != null && !this.spId.equals(other.spId))) {
            return false;
        }
        return true;
    }
    @Override
    public String toString() {
        return "com.rest.api.Workplaces[ spId=" + spId + " ]";
    }
}

所以当我试图访问http://localhost:8080/hiring_challenge/com.rest.api.workplaces/count。它给了我HTTP 500错误tomcat页面。下面是异常的详细信息:

exception
org.jboss.resteasy.spi.UnhandledException: java.lang.NullPointerException
    org.jboss.resteasy.core.SynchronousDispatcher.handleApplicationException(SynchronousDispatcher.java:365)
    org.jboss.resteasy.core.SynchronousDispatcher.handleException(SynchronousDispatcher.java:233)
    org.jboss.resteasy.core.SynchronousDispatcher.handleInvokerException(SynchronousDispatcher.java:209)
    org.jboss.resteasy.core.SynchronousDispatcher.getResponse(SynchronousDispatcher.java:557)
    org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:524)
    org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:126)
    org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:208)
    org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:55)
    org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:50)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
root cause
java.lang.NullPointerException
    com.rest.api.service.AbstractFacade.count(AbstractFacade.java:47)
    com.rest.api.service.WorkplacesFacadeREST.countREST(WorkplacesFacadeREST.java:80)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:606)
    org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:167)
    org.jboss.resteasy.core.ResourceMethod.invokeOnTarget(ResourceMethod.java:269)
    org.jboss.resteasy.core.ResourceMethod.invoke(ResourceMethod.java:227)
    org.jboss.resteasy.core.ResourceMethod.invoke(ResourceMethod.java:216)
    org.jboss.resteasy.core.SynchronousDispatcher.getResponse(SynchronousDispatcher.java:542)
    org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:524)
    org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:126)
    org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:208)
    org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:55)
    org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:50)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)

我试着调试它。结果是EntityManager em在运行时是空的。我为我的EntityManager em检查了PersistenceContext的单位名称。它与我的persistence.xml中指定的相同。我使用Netbeans"从数据库创建RESTful Web服务"从我的本地mysql数据库创建这些文件。有人能帮帮我吗?

更新:我通过添加:

解决了这个问题。
em = Persistence.createEntityManagerFactory("com.rest_hiring_challenge_war_1.0-SNAPSHOTPU").createEntityManager();

放入我的WorkplacesFacadeREST.java的getEntityManager()方法中。然而,我得到了一个没有任何xml返回的页面。所以这是一个新问题…帮忙?

更新:我丢失了mySQL jdbc驱动程序。在补充了这些之后,这个项目成功了。

mySQL jdbc驱动程序缺失。

相关内容

  • 没有找到相关文章

最新更新