jpa初次尝试之No identifier specified for entity问题

jpa初次尝试之No identifier specified for entity问题

项目一直使用mybatis,今天初次尝试使用jpa,然而出师不利,在跑第一个单元测试的时候就报错了,折腾了许久,主要报错信息如下:

2018-08-14 20:05:44.895 ERROR 8632 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: com.mydemo.domain.User
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1699) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:573) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
	...
**Caused by: org.hibernate.AnnotationException: No identifier specified for entity: com.mydemo.domain.User**
	at org.hibernate.cfg.InheritanceState.determineDefaultAccessType(InheritanceState.java:266) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
	at org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:211) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
	at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:731) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
	... 45 common frames omitted

锁定错误信息:

Caused by: org.hibernate.AnnotationException: No identifier specified for entity: com.mydemo.domain.User

于是排查User对象是否设置主键:

@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue
    @Column(name = "user_id")
    private Integer userId;

    @Column(name = "username")
    private String userName;

    @Column
    private String password;
	...

}

发现主键是设置了的,然后开始疯狂地检查jar包依赖是否正确,数据库连接是否正确,数据库user表字段是否与对象匹配,(这里有点太盲目了!!)挨个检查完并没发现什么问题。
有点无望,开始仔细琢磨错误信息,我的大致理解应该就是id的问题,难道是我对错误的理解有误??我开始怀疑自己,于是开始谷歌,终于豁然开朗,这篇文章讲得非常清楚:https://blog.csdn.net/a78270528/article/details/77672977
然后我回去看我的import:

import org.springframework.data.annotation.Id;

果然,是引入了错误的包,换成:

import javax.persistence.*; 

问题终于解决!!

总结:对症下药很重要,切不可急病乱投医。

原文地址:https://www.cnblogs.com/mucheng/p/9477843.html