java.lang.ClassNotFoundException:无法使用 JPA 找到 javax.persistence.Persistence [英] java.lang.ClassNotFoundException: javax.persistence.Persistence cannot be found with JPA
问题描述
我正在练习 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>
用于休眠
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:http://www.eclipse.org/eclipselink/downloads/
- 对于 Hibernate:http://hibernate.org/orm/
一些 JPA 快速入门建议仅添加与 maven 的 JPA API(仅限接口声明)依赖项.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!