'@Transient' 不适用于字段
时间: 2023-07-27 20:33:08 浏览: 139
非常感谢指出,"@Transient" 注解在 JPA 中确实不适用于字段。正确的用法是将它放在实体类的属性的 getter 方法上,而不是字段上。这是因为 JPA 通过 getter 和 setter 方法来访问实体类的属性。
以下是一个示例:
```
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private transient int age;
@Transient
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// getters and setters for other properties
}
```
在上面的代码中,"age" 属性被定义为 transient,表示它不会被持久化到数据库中。同时,它的 getter 方法上添加了 "@Transient" 注解,以告诉 JPA 这个属性不需要持久化。
需要注意的是,如果你使用 Hibernate,"@Transient" 注解也可以放在字段上,但这并不是标准 JPA 的行为。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)