Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.ClassNotFoundException: javax.persistence.Persistence cannot be found with JPA

Tags:

java

jpa

I'm praticing with JPA API. I got an error

java.lang.ClassNotFoundException: javax.persistence.Persistence cannot be found

My code below:

EntityManagerFactory emf;
emf = Persistence.createEntityManagerFactory("mail");
EntityManager em = emf.createEntityManager();
Query query = em.createQuery("SELECT v FROM Version v");
List<Version> versions = query.getResultList();

The error at line emf = Persistence.createEntityManagerFactory("mail");

Any solution?

like image 676
gamo Avatar asked Sep 03 '14 08:09

gamo


1 Answers

You are trying to set up a standalone JPA project. In order to do so you need a JPA provider jars. The two more popular providers are Eclipselink and Hibernate. If you are using maven you can add dependencies to their implementations.

  • For Eclipselink

    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
        <version>2.5.1</version>
    </dependency>
    
  • For Hibernate

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.6.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.3.6.Final</version>
    </dependency>
    

If you are not using maven you can download their implementations from their sites and put it in your classpath.

  • For Eclipselink: http://www.eclipse.org/eclipselink/downloads/
  • For Hibernate: http://hibernate.org/orm/

Some JPA quickstarts are recommending to add only the JPA API (interface declarations only) dependencies with maven.

    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>javax.persistence</artifactId>
        <version>2.1.0</version>
    </dependency>

or

    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.1-api</artifactId>
        <version>1.0.0.Final</version>
    </dependency>

This approach will be successful only in server environment as the server will provide appropriate implementation at runtime.

like image 72
zbig Avatar answered Oct 11 '22 13:10

zbig