網頁

2019/9/11

Spring Data JPA org.hibernate.AnnotationException: No identifier specified for entity 錯誤原因

在設計好Spring Data JPA的實體類別(Entity class)後,啟動時出現org.hibernate.AnnotationException: No identifier specified for entity: <Entity class full qualified name>錯誤。

此錯誤的發生原因是因為掛有@Entity的類別中缺少@Id欄位。

例如下面是導致錯誤發生的entity類別,可以看到少了@Id,也因此導致發生上述錯誤。

package com.abc.demo.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "CUSTOMER")
public class Customer {
    
    @Column(name = "CUST_ID")
    private String custId;
    
    @Column(name = "CUST_NAME")
    private String custName;
    
    // getter and setter...
}

只要在主鍵(Primary Key)對應的欄位屬性前加上@Id即可解決。

package com.abc.demo.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "CUSTOMER")
public class Customer {
    
    @Id // <-- 加上這個
    @Column(name = "CUST_ID")
    private String custId;
    
    @Column(name = "CUST_NAME")
    private String custName;
    
    // getter and setter...
}


沒有留言:

張貼留言