Skip to content

Instantly share code, notes, and snippets.

@milovtim
Forked from mefernandez/Employee.java
Created February 14, 2024 09:15
Show Gist options
  • Save milovtim/b85641492e1592b060fe5a56889f4272 to your computer and use it in GitHub Desktop.
Save milovtim/b85641492e1592b060fe5a56889f4272 to your computer and use it in GitHub Desktop.
Spring Data's Page and @JSONVIEW solution

These two pieces of code above (the PageSerializer class and Spring's @Configuration class) are intended to be included in a Spring Boot application (tested on version 1.4.2).

The custom serializer takes care of serializing org.springframework.data.domain.Page instances returned by a @RestController that uses @JsonView.

It will fully serialize the Page object, albeit not having a matching @JsonView, but will process all @JsonView annotations in the objects contained in that Page.

More on performance using JPA lazy fetching and JSON serializing with @JsonView in this link. https://github.com/mefernandez/spring-jpa-lazy-projections

@Entity
public class Employee {
@Id
@GeneratedValue
private Long id;
@JsonView(SummaryView.class)
private String name;
@JsonView(SummaryView.class)
@ManyToOne(fetch=FetchType.LAZY)
private Department department;
@ManyToOne(fetch=FetchType.LAZY)
private Employee boss;
}
@RestController
public class EmployeeRestController {
@Autowired
private EmployeeRepository employeeRepository;
@JsonView(SummaryView.class)
@RequestMapping(method = RequestMethod.GET, value = "/lazy/employees")
public Page<Employee> search(Pageable pageable) {
return employeeRepository.findAll(pageable);
}
}
public class PageSerializer extends StdSerializer<pageimpl> {
public PageSerializer() {
super(PageImpl.class);
}
@Override
public void serialize(PageImpl value, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeStartObject();
gen.writeNumberField("number", value.getNumber());
gen.writeNumberField("numberOfElements", value.getNumberOfElements());
gen.writeNumberField("totalElements", value.getTotalElements());
gen.writeNumberField("totalPages", value.getTotalPages());
gen.writeNumberField("size", value.getSize());
gen.writeFieldName("content");
provider.defaultSerializeValue(value.getContent(), gen);
gen.writeEndObject();
}
}
@Configuration
public class SpringApplicationConfiguration {
@Bean
public Module jacksonHibernate4Module() {
Hibernate4Module module = new Hibernate4Module();
module.enable(Hibernate4Module.Feature.FORCE_LAZY_LOADING);
return module;
}
@Bean
public Module jacksonPageWithJsonViewModule() {
SimpleModule module = new SimpleModule("jackson-page-with-jsonview", Version.unknownVersion());
module.addSerializer(PageImpl.class, new PageSerializer());
return module;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment