问题描述
我正在使用JPA API。我收到错误
I'm praticing with JPA API. I got an error
java.lang.ClassNotFoundException: javax.persistence.Persistence cannot be found
我的代码如下:
EntityManagerFactory emf;
emf = Persistence.createEntityManagerFactory("mail");
EntityManager em = emf.createEntityManager();
Query query = em.createQuery("SELECT v FROM Version v");
List<Version> versions = query.getResultList();
行 emf = Persistence.createEntityManagerFactory(mail)的错误;
任何解决方案?
推荐答案
您正在尝试设置一个独立的JPA项目。为此,您需要一个JPA提供者jar。两个更受欢迎的提供商是Eclipselink和Hibernate。如果您正在使用maven,则可以向其实现添加依赖项。
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.
-
对于Eclipselink
For Eclipselink
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.1</version>
</dependency>
对于Hibernate
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>
如果您不使用maven,可以下载他们从他们的网站实现并将它放在你的类路径中。
If you are not using maven you can download their implementations from their sites and put it in your classpath.
- 对于Eclipselink:
- 对于Hibernate:
- For Eclipselink: http://www.eclipse.org/eclipselink/downloads/
- For Hibernate: http://hibernate.org/orm/
有些JPA快速入门推荐给仅添加JPA API(仅限接口声明)依赖项与maven。
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>
或
<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.
这篇关于java.lang.ClassNotFoundException:JPA找不到javax.persistence.Persistence的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!