Spring Data Jpa中实体主键问题

时间:2022-05-22 15:11:57
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: cn.merson.redbirds.entity.Store
org.hibernate.AnnotationException: No identifier specified for entity: cn.merson.redbirds.entity.Store

今天在用Spring Boot整合spring-data-jpa时遇到如上的错误,其实这个报错本身很简单,究其原始是因为没有为标注为@Entity的实体类注明主键,当我准备去改错的时候,发现自己分明已经用@Id和@GenerateValue标注在ID上,怎么还会报错了,排查了半天,发现是导错包:import org.springframework.data.annotation.Id;这是Spring提供的;而应该导入javax.persistence.Id,很细微的差别,可能不注意看就错了而且很难去排查问题;
另外:org.springframework.data.annotation.Id和javax.persistence.Id接口声明都一样,
这是javax提供的:
package javax.persistence;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Id {
}
这是spring的:
package org.springframework.data.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
public @interface Id {
}
区别在于:org.springframework.data.annotation.Id是spring用来支持MongoDB等非关系型数据库的持久化(spring-data-mongodb,spring-data-solr等);在JPA中是没有实现的。javax.persistence.Id适用于关系型的数据