How to use persistence.xml and hibernate.cfg.xml in JUnit tests via eclipse?

自闭症网瘾萝莉.ら 提交于 2019-12-21 13:03:37

问题


I have been searching for an answer during quite a long time before coming here and ask this question. My problem is very simple : I cannot run any JUnit test when using the JPA Entity Manager API. It seems that my test is not reading the persistence.xml file.

When I call new Configuration().configure().buildSessionFactory(), it works like a charm but an exception is thrown when calling Persistence.createEntityManagerFactory("myapp") is:

javax.persistence.PersistenceException: No Persistence provider for EntityManager named myapp at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:69) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47) at com.myapp.Test01.setUpBeforeClass(Test01.java:22)

My JavaSE project has the following structure :

myapp
++src/main/java
   ++com.myapp.model
      ++// My entity classes are here
++src/test/java
   ++com.myapp
      ++Test01.java
++src/main/resources
  ++hibernate.cfg.xml
  ++META-INF 
    ++persistence.xml

and persistence.xml looks like:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    version="2.0">
    <persistence-unit name="myapp" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
            <property name="hibernate.ejb.cfgfile" value="hibernate.cfg.xml"></property> 
        </properties>
    </persistence-unit>
</persistence>

Do you have any idea how to solve this issue ?

Thank you very much for your help.


回答1:


My guess would be that org.hibernate.ejb.HibernatePersistence is not on your classpath. That's not in the main Hibernate jar, it's in the hibernate-entitymanager or some such jar.

A couple of quick experiments would be to do, in the code immediately before the call to Persistence.createEntityManagerFactory():

System.out.println(getClass().getResource("META-INF/persistence.xml"));

And:

System.out.println(Class.forName("org.hibernate.ejb.HibernatePersistence"));

It would also be wise to check that Eclipse is copying your resources; do a Project > Clean and then look in your Eclipse build output directory to see if persistence.xml is where you expect. I have sometimes run into cases where Eclipse doesn't copy resources for some reason or other.




回答2:


Put the configuration in src/test/resources/META-INF.



来源:https://stackoverflow.com/questions/12885295/how-to-use-persistence-xml-and-hibernate-cfg-xml-in-junit-tests-via-eclipse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!