網頁

2021/4/12

Spring Data JPA @Transient 沒有作用

Spring Data JPA的entity屬性前掛上@Transient來忽略此欄位的映射卻沒有效果,導致錯誤Caused by: org.hibernate.MappingException: Could not determine type for: java.lang.String, at table: employee, for columns: [org.hibernate.mapping.Column(phone)]

例如entity類Employee如下。phone欄位前掛了@Transient但沒作用。問題原因出在應該引用javax.persistence.Transient,而非org.springframework.data.annotation.Transient

Employee

package com.abc.demo.entity

import org.springframework.data.annotation.Transient; // 應改成javax.persistence.Transient

import java.io.Serializable;

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

@Table(name = "EMPLOYEE")
@Entity
public class Employee implements Serializable {
  
  @Id
  @Column(name = "ID")
  private long id;
  
  @Column(name = "NAME")
  private String name;
  
  @Transient
  private String phone;
  
  // getters and setters

}

這是因為Spring Data JPA是走JPA所以只認得javax.persistence.Transient。至於org.springframework.data.annotation.Transient是用在其他Spring Data框架如Spring Data JDBC、Spring Data Redis、Sprnig Data MongoDB等,效果相同。


沒有留言:

張貼留言