此位置不允许使用注释@PersistenceUnit

时间:2016-08-15 13:15:56

标签: java jpa jdbc

和其他人一样,我遇到了问题:

  

“此地点不允许使用注释@PersistenceUnit

我的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="XCCAdminUnit">
          <jta-data-source>java:comp/env/jdbc/MyDataSource</jta-data-source>

          <properties>
            <property name="openjpa.LockTimeout" value="30000" />
            <property name="openjpa.jdbc.TransactionIsolation" value="read-committed" />
            <property name="openjpa.Log" value="none" />
            <property name="openjpa.jdbc.UpdateManager" value="operation-order" />
            <property name="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver"/>
        </properties>
    </persistence-unit>
</persistence>

我的代码:

package XCCAdminServlet;

import java.io.IOException;
import javax.annotation.Resource;
import javax.annotation.Resource.AuthenticationType;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

/**
 * Servlet implementation class XCCAdminMain
 */
@WebServlet({"/XCCAdminMain", "/xcc-admin/rest/query", "/xcc-admin/test/query"})
@Resource(name = "jdbc/MyDataSource", type = javax.sql.DataSource.class, shareable = true, authenticationType = AuthenticationType.CONTAINER)
public class XCCAdminMain extends HttpServlet {
  private static final long serialVersionUID = 1L;

  @PersistenceUnit(unitName = "XCCAdminUnit")
  /**
   * @see HttpServlet#HttpServlet()
   */
  public XCCAdminMain() {
    super();
  }

  @GET
  @Path("/{param}")
  public Response getQuery(@PathParam("param") String msg) throws ServletException {
    return Response.status( 200 ).entity( "Get Request received, queryparam: " + msg ).build();
  }



}

我该怎么做才能解决这个问题?

2 个答案:

答案 0 :(得分:1)

您必须使用@PersistenceContext注释将EntitiyManager bean注入您的servlet。此批注具有unitName属性,您可以按如下方式设置:

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

答案 1 :(得分:-1)

使用此

@PersistenceUnit(unitName = "XCCAdminUnit")
private EntityManager entityManager;

因此,@PersistenceUnit注释必须注入javax.persistence.EntityManager bean。