SpringDataJPA笔记(11)-Transient注解

SpringDataJPA笔记(11)-Transient注解

在 JAVA种,只要该类实现了Serilizable接口,然后在不需要序列化的属性前添加关键字transient,则序列化对象的时候会忽略transient修饰的属性

我们在定义实体类的时候,有一些属性我们不需要持久化到数据库,这种时候我们就可以使用Transient注解,用于标注该字段不需要添加到数据库表,而且即使实体类没有实现Serilizable接口,也会忽略该属性

例如如下一个实体类

@Data
@Entity
@Table(name = "transient_tb")
public class TransientEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Transient
    private String trrr;
}

在实际数据库中查看该表的字段,依然没有该trrr字段

CREATE TABLE transient_tb (
id bigint(20) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

但是我们通常要求实体类还是要实现Serilizable接口,因为这样可以让实体类序列化和反序列化,通过流的方式被传递

通常在使用Transient注解的时候,会发现有两个包同时有这个注解,在不同的情况下需要引入的是不同的包注解

在这里插入图片描述

在使用MySQL的时候需要引入的是

import javax.persistence.Transient;

在使用MongoDB的时候需要引入是

import org.springframework.data.annotation.Transient;

这点需要注意一下 不要引入了错误的包,从而达不到想要的效果

这是因为

javax.persistence.Transient 是标准JPA的注解,并不适用与MongoDB,而org.springframework.data.annotation.Transient是spring的注解,这个才对MongoDB有效

https://docs.spring.io/spring-data/data-document/docs/current/reference/html/#mapping-usage-annotations

欢迎关注微信交流
在这里插入图片描述

你可能感兴趣的:(springboot,jpa)