当前位置: 首页 > 知识库问答 >
问题:

在使用Junit测试用例运行Maven build时获得“没有EntityManager命名的持久性提供程序”

龙俊英
2023-03-14

在运行maven构建时,Junit获得“EntityManager没有持久性提供程序命名”错误。无法识别代码中缺少的内容。

主要类别:

public class ApprovalHistory {

    @PersistenceContext(unitName = "Approval_History")  
    private Logger logger = LoggerFactory.getLogger(ApprovalHistory.class);

    public EntityManagerFactory emfactory = null;

    final String JDBC_URL_H2DB = "jdbc:h2:file:./APApproval/ApprovalHistoryH2DB";
    final String JDBC_USERNAME_H2DB = "";
    final String JDBC_PASSWORD_H2DB = "";

    final String JDBC_DRIVER_SQL = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    final String JDBC_DRIVER_H2 = "org.h2.Driver";
    final String JDBC_DRIVER_HSQL = "org.hsqldb.jdbc.JDBCDriver";

    final String PERSISTANCE_UNIT_NAME = "Approval_History";

    final String SELECT_BO_TABLE = "SELECT bobj FROM BusinessObjectTable bobj where bobj.docId =:";
    final String SELECT_COMMENT_TABLE = "SELECT comment FROM CommentTable comment where comment.actionTable.id IN :";
    final String SELECT_REASON_TABLE = "SELECT reason FROM ReasonTable reason where reason.actionTable.id IN :";    

    public ApprovalHistory()
    {
        try {
            createEntityManagerFactory();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public void insertData(List<ApprovalHistoryModel> historyList){

        if(historyList != null && !historyList.isEmpty())
        {
            EntityManager entitymanager = null;

            try
            {           
                entitymanager = getEntityManager();
                entitymanager.getTransaction().begin(); 


                ApprovalHistoryModel firstItem = historyList.get(0);

                ActionTable a = new ActionTable(firstItem.actionType, firstItem.tenantId, firstItem.comment, firstItem.reason);

                for(ApprovalHistoryModel h : historyList) 
                {
                    a.getBusinessObjects().add(new BusinessObjectTable(h.userName, h.taskId, h.docId, h.objectIdentifier1, h.objectIdentifier2, h.objectIdentifier3,h.tenantId));
                }

                entitymanager.persist(a);

                entitymanager.getTransaction().commit();                    
            }
            catch (RuntimeException e) {
                if(entitymanager!=null && entitymanager.getTransaction().isActive()) {
                    entitymanager.getTransaction().rollback();
                }
                throw e;
            }

            finally{
                closeEntityManager(entitymanager);
            }
        }
    }


    public List<ApprovalHistoryModel> getApprovalHistory(String docID) throws Exception
    {
        logger.info("=ApprovalConnector=: start of getApprovalHistory()");

        List<ApprovalHistoryModel> historyModels = new ArrayList<ApprovalHistoryModel>();

        if(docID!=null && !docID.isEmpty()) {
        EntityManager entitymanager = null;

        try
        {
            entitymanager = getEntityManager();     

            TypedQuery<BusinessObjectTable> bobjquery =  entitymanager.createQuery(SELECT_BO_TABLE+"DocID ",BusinessObjectTable.class);
            bobjquery.setParameter("DocID", docID);         
            List<BusinessObjectTable> bobjs = bobjquery.getResultList();    

            if(bobjs!=null){
                for (BusinessObjectTable bobj : bobjs) {
                    ActionTable a = bobj.getActionTable();

                    ApprovalHistoryModel history = new ApprovalHistoryModel();
                    history.docId = bobj.getDocId();
                    history.taskId = bobj.getApprovalItemId();
                    history.userName = bobj.getUserName();

                    logger.debug("=ApprovalConnector=: getApprovalHistory(): documentID - "+bobj.getDocId());
                    history.actionType = a.getActionType();

                    logger.debug("=ApprovalConnector=: getApprovalHistory(): actionType - "+ history.actionType);

                    history.actionDate = ISODateTimeFormat.dateTime().print(new DateTime(a.getActionDate()));
                    history.objectIdentifier1 = bobj.getObjectIdentifier1();
                    history.objectIdentifier2=bobj.getObjectIdentifier2();
                    history.objectIdentifier3 = bobj.getObjectIdentifier3();
                    history.tenantId = a.getTenantId();

                    history.comment = a.getComment()!=null?a.getComment().getComment():"";
                    history.reason = a.getReason()!=null?a.getReason().getReason():"";

                    historyModels.add(history);
                }

            }
            logger.info("=ApprovalConnector=: end of getApprovalHistory()");
        }
        finally{
            closeEntityManager(entitymanager);
        }   
    }

        return historyModels;
    }

    public void createEntityManagerFactory() throws Exception
    {               
        Map<String, String> persistenceMap = new HashMap<String, String>();

        String jdbcDriver = getJdbcDriverName(JDBC_URL_H2DB);

        persistenceMap.put("javax.persistence.jdbc.driver", jdbcDriver);
        persistenceMap.put("javax.persistence.jdbc.url", JDBC_URL_H2DB);

        if (!JDBC_USERNAME_H2DB.isEmpty()) {
            persistenceMap.put("javax.persistence.jdbc.user", JDBC_USERNAME_H2DB);
        }
        if (!JDBC_PASSWORD_H2DB.isEmpty()) {
            persistenceMap.put("javax.persistence.jdbc.password", JDBC_PASSWORD_H2DB);
        }

        persistenceMap.put("eclipselink.session-name",System.currentTimeMillis() + "");

        this.emfactory = Persistence.createEntityManagerFactory(PERSISTANCE_UNIT_NAME, persistenceMap); 

    }

    public EntityManager getEntityManager()
    {               
        EntityManager entitymanager = this.emfactory.createEntityManager();
        return entitymanager;
    }

    public void closeEntityManager(EntityManager entitymanager)
    {
        if(entitymanager!=null)
            entitymanager.close();      
    }
    public void closeEntityManagerFactory()
    {
        if(this.emfactory!=null)
            this.emfactory.close();
    }

    private String getJdbcDriverName(String jdbcUrl) {
        if (jdbcUrl.startsWith("jdbc:sqlserver"))
            return JDBC_DRIVER_SQL;
        if (jdbcUrl.startsWith("jdbc:h2"))
            return JDBC_DRIVER_H2;
        if (jdbcUrl.startsWith("jdbc:hsqldb"))
            return JDBC_DRIVER_HSQL;
        return null;
    }



Test Calss:

    public class ApprovalHistoryTest {

        ApprovalHistory approvalHistory = new ApprovalHistory();

        @Before
        public void setUp() throws Exception {

            List<ApprovalHistoryModel> actionHistoryModels = new ArrayList<ApprovalHistoryModel>();     

                for(int i=0;i<=2;i++){
                ApprovalHistoryModel history = new ApprovalHistoryModel();
                String comment = "comment no. " + i;
                String reason = "reason no. " + i;
                String userName = "User" + i;
                history.taskId = "321YZ61_0026CV7Z0000XB" + i;
                history.actionDate = ISODateTimeFormat.dateTime().print(new DateTime(new Date()));
                history.actionType = i;
                history.comment = comment.trim();
                history.docId = "321YZ61_026CV7Z0000TD" + i;
                history.userName = userName;
                history.reason = reason;

                actionHistoryModels.add(history);

                }   
            approvalHistory.insertData(actionHistoryModels);
        }

        @After
        public void tearDown() throws Exception {
            DeleteApprovalHistory history = new DeleteApprovalHistory();
            try{
            history.purgeRecord(0,"DAYS");  
            approvalHistory.closeEntityManagerFactory();
        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }


        @Test()
        public void test() {
            //ApprovalHistory approvalHistory = new ApprovalHistory();
            List<ApprovalHistoryModel> historyList = new ArrayList<ApprovalHistoryModel>(); 
            for(int i=0;i<=2;i++){
            ApprovalHistoryModel history = new ApprovalHistoryModel();
              try {
                  Thread.sleep(1000);
                  historyList=approvalHistory.getApprovalHistory(history.docId);
                  assertEquals("321YZ61_0026CV7Z0000XB" + i,historyList.get(i).taskId);`enter code here`
                  assertEquals("comment no. " + i,historyList.get(i).comment);
                  assertEquals("User" + i,historyList.get(i).userName);
                  assertEquals("reason no. " + i,historyList.get(i).reason);
                  assertEquals(i,historyList.get(i).actionType);


            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
            }
        }

    }

Persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
    xmlns="http://java.sun.com/xml/ns/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_1.xsd">

  <persistence-unit name="Approval_History" transaction-type="RESOURCE_LOCAL">
    <class>com.perceptivesoftware.apapproval.history.ActionTable</class>
    <class>com.perceptivesoftware.apapproval.history.BusinessObjectTable</class>
    <class>com.perceptivesoftware.apapproval.history.CommentTable</class>
    <class>com.perceptivesoftware.apapproval.history.ReasonTable</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
     <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <properties>
      <property name="eclipselink.ddl-generation" value="create-or-extend-tables" />
      <property name="eclipselink.logging.level.sql" value="FINE"/>
      <property name="eclipselink.logging.parameters" value="true"/>
      <property name="eclipselink.multitenant.tenants-share-cache" value="true" />          
    </properties>
  </persistence-unit>
</persistence>

错误::

共有1个答案

闻人越
2023-03-14

您注释了错误的属性:

@PersistenceContext(unitName = "Approval_History")  
private Logger logger = LoggerFactory.getLogger(ApprovalHistory.class);

应该是:

@PersistenceContext(unitName = "Approval_History")  
public EntityManager em;

@PersistenceContext注释将EntityManager注入到代码中,该代码是从与您指定的持久化单元关联的EntityManager工厂创建的(“在您的情况下为“批准历史”)。

 类似资料:
  • 我得到了这个错误: 线程“main”javax中出现异常。坚持不懈PersistenceException:在javax上没有名为EmployeeDb的EntityManager的持久性提供程序。坚持不懈坚持不懈javax上的createEntityManagerFactory(Persistence.java:85)。坚持不懈坚持不懈staffManagement的createEntityMan

  • 问题内容: 我在目录下使用相同的名字。然后,我用以下代码调用它: 但是,我收到以下错误消息: 这是: 它应该在类路径中。但是,我得到了上面的错误。 问题答案: 在之后,定义持久性提供程序名称:

  • 我试图在Eclipse中测试我的hibernate maven应用程序,当我运行获取enttity类名称的方法时,我得到了以下异常: 这是persistence.xml: 这是使用以下方法的类: 波姆。xml: 我尝试更改持久性的版本号、更改xmlns、提供程序的名称,但仍然是例外。

  • 我在REST服务器上工作,同时学习EJB\Hibernate。当服务调用DAO时,我面临一个问题,即它找不到我的持久性单元。 在本例中,我得到“无法为unitName PersistenceUnit检索EntityManagerFactory” 然后我试试这个: null pom.xml

  • 我正在尝试调用persistence.xml来显示Netbean IDE中数据库中的一些数据。我已经查看并尝试了以前用户提出的不同方法,但我仍然无法解决这个问题。 我用这个来称呼持久性单元, 这是我试图运行文件时返回的结果, 这是第805行,错误似乎就是从这里产生的 如前所述, 我已经在持久化单元名称下添加了提供者, 我已经确保持久性是单元在META-INF文件夹中, 它在类路径中,所以我不确定错

  • 我正在使用JPA开发一个JavaSE应用程序。不幸的是,调用后我得到了: 下面你会发现: 调用并意外返回 我的坚持。xml文件 我的项目结构 我的代码片段: 我的坚持。xml: 我的项目结构: