Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this short tutorial, we’ll learn the difference between the @JsonIgnore and @Transient annotations.

2. @JsonIgnore

We use the @JsonIgnore annotation to specify a method or field that should be ignored during serialization and deserialization processes. This marker annotation belongs to the Jackson library.

We often apply this annotation to exclude fields that may not be relevant or could contain sensitive information. We use it on a field or a method to mark a property we’d like to ignore.

Firstly, let’s create a simple Person class with several fields:

class Person implements Serializable {

    private Long id;

    private String firstName;

    private String lastName;

    // getters and setters
}

Now, let’s suppose we don’t want to show the id field in the JSON representation of the Person object. Let’s exclude the field using the @JsonIgnore annotation:

class Person implements Serializable {

    @JsonIgnore
    private Long id;

    private String firstName;

    private String lastName;

    // getters and setters
}

Finally, let’s write a test to make sure ObjectMapper ignores the id field:

@Test
void givenPerson_whenSerializing_thenIdFieldIgnored() 
  throws JsonProcessingException {

    Person person = new Person(1L, "My First Name", "My Last Name");
    String result = new ObjectMapper().writeValueAsString(person);

    assertThat(result, containsString("firstName"));
    assertThat(result, containsString("lastName"));
    assertThat(result, not(containsString("id")));
}

3. @Transient

On the other hand, we use the @Transient annotation to indicate the Java Persistence API (JPA) should ignore the field when mapping objects to a database. When we mark a field with this annotation, the JPA won’t persist the field and it won’t retrieve its value from the database.

Now, let’s create a User class:

@Entity
@Table(name = "Users")
class User implements Serializable {

    @Id
    private Long id;

    private String username;

    private String password;

    private String repeatedPassword;

    // getters and setters
}

Let’s exclude the repeatedPassword field from the database representation of a User object with the @Transient annotation:

@Entity
@Table(name = "User")
class User implements Serializable {

    @Id
    private Long id;

    private String username;

    private String password;

    @Transient
    private String repeatedPassword;

    // getters and setters
}

When we persist a User object to the database, the JPA won’t save repeatedPassword value to the database. Additionally, JPA ignores the field when loading objects from the database:

@Test
void givenUser_whenSave_thenSkipTransientFields() {
    User user = new User(1L, "user", "newPassword123", "newPassword123");
    User savedUser = userRepository.save(user);

    assertNotNull(savedUser);
    assertNotNull(savedUser.getPassword());
    assertNull(savedUser.getRepeatedPassword());
}

However, the @Transient annotation won’t exclude a field from serialization:

@Test
void givenUser_whenSerializing_thenTransientFieldNotIgnored() throws JsonProcessingException {

    User user = new User(1L, "user", "newPassword123", "newPassword123");
    String result = new ObjectMapper().writeValueAsString(user);

    assertThat(result, containsString("user"));
    assertThat(result, containsString("repeatedPassword"));
}

4. Conclusion

In this article, we learned the differences between the @JsonIgnore and @Transient annotations.

To sum up, both annotations are used to indicate fields that should be ignored when performing certain operations. The @JsonIgnore annotation excludes the fields from the JSON representation. The @Transient annotation omits them from the database representation.

As always, the full source code of the article is available over on GitHub.

Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE
Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – Persistence (eBook) (cat=Persistence)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.