Spring Data JPA在存取資料表時發生java.sql.SQLSyntaxErrorException: ORA-00904: "TABLE"."COLUMN": 無效的 ID錯誤。
原因很簡單,就是entity欄位名稱和資料表欄位名稱不一致。
例如資料表EMPLOYEE欄位如下。
EMPLOYEE
| COLUMN_NAME | DATA_TYPE |
|---|---|
| ID | NUMBER |
| NAME | VARCHAR2 |
| VARCHAR2 | |
| AGE | NUMBER |
對映的entity類Employee如下,email的欄位名稱錯寫成MAIL了。
Employee
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
@Id
@Column(name = "ID")
private long id;
@Column(name = "NAME")
private String name;
@Column(name = "MAIL") // <-- 正確為EMAIL,錯寫成MAIL
private String email;
@Column(name = "AGE")
private int age;
// getter and setter ommitted
}
則在EmployeeRepository查詢該表時會出現java.sql.SQLSyntaxErrorException: ORA-00904: "EMPLOYEE0_"."MAIL": 無效的 ID錯誤。
EmployeeRepository
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
這個錯誤在以下情況常會找不出問題原因,也就是entity的@Table錯設成另一個很類似的資料表名稱,且該資料表也同時存在,直覺認為是欄位名稱設錯了,但實際上是映射到錯誤的資料表所導致。
例如下面Employee的@Table(name = "EMPLOYER"),且EMPLOYER也存在,這樣就導致用錯誤的entity欄位去存取並引發ORA-00904: invalid identifier錯誤。
Employee
@Entity
@Table(name = "EMPLOYER") // <-- 應該是EMPLOYEE,但錯設為EMPLOYER
public class Employee {
@Id
@Column(name = "ID")
private long id;
@Column(name = "NAME")
private String name;
@Column(name = "EMAIL")
private String email;
@Column(name = "AGE")
private int age;
// getter and setter ommitted
}
- Spring Data JPA @Query nativeQuery org.hibernate.exception.SQLGrammarException: could not execute query 錯誤
- Spring Data JPA @Query nativeQuery ORA-03001: unimplemented feature 錯誤
- Spring Data JPA org.hibernate.AnnotationException: No identifier specified for entity 錯誤原因
- Spring Data JPA org.springframework.orm.jpa.JpaSystemException: identifier of an instance of Entity was altered from x to y錯誤
沒有留言:
張貼留言