最近写一个web项目,Spring Boot 使用的最新稳定版本2.0.4,
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
但是当尝试集成Spring Data JPA 的时候发现一个很奇怪的现象,在之前2.0.0 版本时引入下面这个依赖
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
在实体类中就可以直接使用@Entity 注解的,但是现在却怎么样也提示 不出来。
故障分析:
经过思考,注解引入的是这三个包,但是现在提示不出来 应该是缺少这个包
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id;
那么这个包来源于哪里呢?
查资料可知,这个包是hibernate-jpa-2.1-api.jar里面的
解决方案
最优解决方案:
如果是Spring Boot 项目直接使用JPA starters 就好了
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
因为这个依赖中spring-boot-starter-data-jpa 添加了Hibernate 相关的依赖.
在这里由衷感谢@weixin_44545768的指正.
spring-boot-starter-data-jpa-2.1.4.RELEASE.pom 中依赖如下:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> <version>2.1.4.RELEASE</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> <version>2.1.4.RELEASE</version> <scope>compile</scope> </dependency> <dependency> <groupId>javax.transaction</groupId> <artifactId>javax.transaction-api</artifactId> <version>1.3</version> <scope>compile</scope> </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.3.9.Final</version> <scope>compile</scope> <exclusions> <exclusion> <artifactId>jboss-transaction-api_1.2_spec</artifactId> <groupId>org.jboss.spec.javax.transaction</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>2.1.6.RELEASE</version> <scope>compile</scope> <exclusions> <exclusion> <artifactId>aspectjrt</artifactId> <groupId>org.aspectj</groupId> </exclusion> <exclusion> <artifactId>jcl-over-slf4j</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.1.6.RELEASE</version> <scope>compile</scope> </dependency> </dependencies>
解决方案二:
如果不是Spring Boot 项目,那么添加这个依赖即可:
http://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api/1.0.2.Final
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2.Final</version>
</dependency>