我根据“Spring in Action”第11章创建了一个Spring JPA示例。
Java配置代码:
@Bean
public JpaVendorAdapter jpaVendorAdapter() {
System.out.println("hello");
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
System.out.println(adapter);
adapter.setDatabase(Database.MYSQL);
adapter.setShowSql(true);
adapter.setGenerateDdl(false);
adapter.setDatabasePlatform("org.hibernate.dialect.MySQLDialect");
return adapter;
}
@Bean
public EntityManagerFactory entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
emfb.setDataSource(dataSource);
//emfb.setPersistenceUnitName("test");
emfb.setJpaVendorAdapter(jpaVendorAdapter);
emfb.setPackagesToScan("com.springinaction.test");
EntityManagerFactory emf = emfb.getObject();
System.out.println(emf);
return emf;
}
@Bean
public PlatformTransactionManager annotationDrivenTransactionManager(EntityManagerFactory emf) {
//System.out.println(emf);
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
与Spring JPA相关的Maven依赖项:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
该程序运行良好,直到这行代码:
System.out.println("hello");
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
并失败并显示以下错误消息:
hello
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class com.springinaction.test.JdbcConfig: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.orm.jpa.JpaVendorAdapter com.springinaction.test.JdbcConfig.jpaVendorAdapter()] threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/ejb/HibernatePersistence
有人对我说,原因可能是缺少hibernate-entitymanger.jar,但我在本地Maven存储库中找到了这个jar。
有人说理由缺少ejb3-persistence.jar,但我找不到Maven groupId / artifactId。
有人可以向我解释一下吗?
答案 0 :(得分:1)
类org.hibernate.ejb.HibernatePersistence是hibernate-entitymanager jar的一部分。请检查此jar是否在项目类路径中或部署的war文件中。还要检查这个jar文件的版本。而不是提供hibernate-core和hibernate-jpa,你应该在pom.xml中提供hibernate-entitymanager依赖,这将下载所有必需的依赖项。您可以在https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager/5.2.2.Final
查看相同内容<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.2.Final</version>
</dependency>
Spring In Action的源代码位于https://manning-content.s3.amazonaws.com/download/9/ef4e0ef-b7bd-4ab8-857d-eb635d18d425/SpringiA4_SourceCode.zip。您可以检查build.gradle文件是否使用了依赖项。