简体   繁体   English

如何在一个简单的Servlet中使用Spring Data JPA?

[英]How to use Spring Data JPA in a simple Servlet?

I'm very new to Spring, but I am working on a project which is using Spring Data JPA to generate repositories for JPA entities. 我是Spring的新手,但我正在开发一个使用Spring Data JPA为JPA实体生成存储库的项目。

I'm currently adding a simple module to be able to show some data on a webpage. 我目前正在添加一个简单的模块,以便能够在网页上显示一些数据。 I have added a Servlet, but I am having trouble accessing the repositories from there. 我添加了一个Servlet,但是我无法从那里访问存储库。

I have added a ContextLoaderListener in web.xml, I'm referencing the jpa:repositories and persistence.xml in the applicationContext.xml, but I'm currently stuck with this exception: 我在web.xml中添加了一个ContextLoaderListener,我在applicationContext.xml中引用了jpa:repositories和persistence.xml,但我现在仍然遇到这个异常:

No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0. 没有定义[javax.persistence.EntityManagerFactory]类型的唯一bean:期望的单个bean但找到0。

But when I add an EntityManagerFactory in persistence.xml I get the following cryptic message: 但是当我在persistence.xml中添加一个EntityManagerFactory时,我收到以下神秘消息:

java.lang.IllegalAccessError: tried to access field org.hibernate.engine.spi.CascadeStyle.STYLES from class org.hibernate.engine.spi.EJB3CascadeStyle java.lang.IllegalAccessError:尝试从类org.hibernate.engine.spi.EJB3CascadeStyle访问字段org.hibernate.engine.spi.CascadeStyle.STYLES

My question is: is what I am trying to do even possible? 我的问题是:我正在尝试做甚么可能吗? And if so, how? 如果是这样,怎么样? Or should I just bite the bullet and use Spring MVC or something else entirely? 或者我应该咬紧牙关并完全使用Spring MVC或其他东西?

Note: this is just for a one-page web site and I'm trying to keep it as simple as possible. 注意:这仅适用于单页网站,我试图尽可能简单。

In order to use Spring Data JPA you need to configure the underlying JPA implementation as you would typically do in Spring, see for example, infrastructure.xml and META-INF/persistence.xml in spring-data-jpa-showcase (since Spring 3.1 you can get rid of persistence.xml if you use packagesToScan property of LocalContainerEntityManagerFactoryBean ). 为了使用Spring Data JPA,您需要像在Spring中一样配置底层JPA实现,例如,参见spring-data-jpa-showcase infrastructure.xmlMETA-INF/persistence.xml (自Spring 3.1起)如果使用LocalContainerEntityManagerFactoryBean packagesToScan属性,则可以删除persistence.xml

Your second problem with IllegalAccessError looks like a classloading problem caused by presence of different versions of Hibernate jars in classpath. IllegalAccessError第二个问题看起来像是由类路径中存在不同版本的Hibernate jar引起的类加载问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM