简体   繁体   中英

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.

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.

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:

No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0.

But when I add an EntityManagerFactory in persistence.xml I get the following cryptic message:

java.lang.IllegalAccessError: tried to access field org.hibernate.engine.spi.CascadeStyle.STYLES from class org.hibernate.engine.spi.EJB3CascadeStyle

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?

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 ).

Your second problem with IllegalAccessError looks like a classloading problem caused by presence of different versions of Hibernate jars in classpath.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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