Home > AI > Backend > SpringBoot > mysql-connector-java >

@Transient effect on Serializable

It has no effect, you should transient keyword instead.

Example:

User.java

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "Users")
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String email;

    private String password;

    private transient Date loginTime;

}

TestRepository.java

@SpringBootTest
class Demo11ApplicationTests {


    @Test
    public void test_serializable() throws IOException, ClassNotFoundException {
        User u = new User();
        u.setEmail("test@fengcaoculture.com");
        u.setLoginTime(new Date());

        // write to file
        FileOutputStream fileOutputStream = new FileOutputStream("person.txt");
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(u);
        objectOutputStream.flush();
        objectOutputStream.close();

        FileInputStream fileInputStream = new FileInputStream("person.txt");
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        User u2 = (User) objectInputStream.readObject();
        objectInputStream.close();


        assertTrue(u2.getEmail().equals(u.getEmail()));
        assertNull(u2.getLoginTime());
    }
}

Leave a Reply