Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering GORM classes from Spring Boot

I'm trying to write a simple Spring Boot controller that renders a GORM instance and failing.

Here's a shortened version of my code:

@RestController
@RequestMapping("/user")
class UserController {
    @RequestMapping(value='/test', method=GET)
    User test() {
        return new User(username: 'my test username')
    }
}

I get the following error message:

Could not write JSON: No serializer found for class org.springframework.validation.DefaultMessageCodesResolver and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: users.domain.User["errors"]->grails.validation.ValidationErrors["messageCodesResolver"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.springframework.validation.DefaultMessageCodesResolver and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: users.domain.User["errors"]->grails.validation.ValidationErrors["messageCodesResolver"])

The error seems to be caused by extra properties injected by GORM. What is the proposed solution for this? Will this eventually be solved in gorm-hibernate4-spring-boot? Should I simply disable SerializationFeature.FAIL_ON_EMPTY_BEANS (I don't have a lot of experience with Jackson so I'm not entirely sure what side effects this may have)? Should I use Jackson's annotations to solve the problem? Any other options?

like image 773
Gregor Petrin Avatar asked Jul 04 '14 14:07

Gregor Petrin


1 Answers

I've found a way to get rid of the error using this code:

@Component
class ObjectMapperConfiguration implements InitializingBean {

    @Autowired
    ObjectMapper objectMapper

    @Override
    void afterPropertiesSet() {
        def validationErrorsModule = new SimpleModule()
        validationErrorsModule.addSerializer(ValidationErrors, new ErrorsSerializer())
        objectMapper.registerModule(validationErrorsModule)
    }

}

class ErrorsSerializer extends JsonSerializer<ValidationErrors> {
    @Override
    void serialize(ValidationErrors errors, JsonGenerator jgen, SerializerProvider provider) {
        jgen.writeStartObject()
        jgen.writeEndObject()
    }
}

Obviously this solution is far from perfect as it simply nukes all validation errors but right now it is good enough for me. I am pretty sure the Spring Boot team will have to address this issue eventually as the GORM objects are also being serialized with some internal Hibernate properties like attached. I'm not accepting this answer as it is not an acceptable solution for most scenarios, it basically just squelches the exception.

like image 157
Gregor Petrin Avatar answered Oct 13 '22 09:10

Gregor Petrin