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

在初次尝试使用Spring Data JPA时遇到Noidentifierspecifiedforentity错误,通过排查发现是由于导入了错误的@Id注解包导致的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.youkuaiyun.com/a78270528/article/details/77672977
然后我回去看我的import:

import org.springframework.data.annotation.Id;

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

import javax.persistence.*; 

问题终于解决!!

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

转载于:https://www.cnblogs.com/mucheng/p/9477843.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值