Skip to content

Instantly share code, notes, and snippets.

@evonsdesigns
Last active April 16, 2018 15:24
Show Gist options
  • Save evonsdesigns/a79f81868fe43ca32ee4eb7341d8b635 to your computer and use it in GitHub Desktop.
Save evonsdesigns/a79f81868fe43ca32ee4eb7341d8b635 to your computer and use it in GitHub Desktop.
Using jackson-datatype-hibernate5@2.9.5, spring-boot-starter@2.0.1.RELEASE, spring-boot-starter-web@2.0.1.RELEASE, spring-boot-starter-data-jpa@2.0.1.RELEASE

The following example shows how by disable the USE_TRANSIENT_ANNOTATION feature, you can include @Transient pojo fields in your serialized json responses.

Application.java

@SpringBootApplication
public class Application {

    ...

    @Bean
    ObjectMapper myObjectMapper() {
        Hibernate5Module m = new Hibernate5Module();
        m.disable(Hibernate5Module.Feature.USE_TRANSIENT_ANNOTATION);
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(m);
        return mapper;
    }
}

Pojo.java

@Entity
public class SimplePojo {
    @Transient
    private static final String transientProperty = "SomethingToInclude";

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    public void setId(Long id) {
        this.id = id;
    }

    public Long getId() {
        return id;
    }

    @Transient
    @JsonGetter(value = "transientProperty")
    public String getType() {
        return type;
    }

Controller.java

@RestController
public class SimplePojoController {
	@RequestMapping(
	      value = "/simple",
	      method = RequestMethod.GET
	  )
	  public @ResponseBody SimplePojo get()
	      throws Exception {
	    return new SimplePojo();
	  }
}

Rest endpoint Output

{
	"id": 1,
	"transientProperty": "SomethingToInclude"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment