Issue
I am trying to create a basic REST service using Spring Boot that returns POJOs created from a database using Hibernate and then are transformed into JSON and returned to the REST call.
I can get regular non-Hibernate POJOs to be returned as JSON, but for Hibernate objects I am getting this error:
Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.example.springboottest.model.Person_$$_jvst48e_0["handler"])
Here is my code:
Person.java
@Entity
@Table(name = "people")
public class Person implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String nameLast;
private String nameFirst;
@Temporal(TemporalType.DATE)
private Date dob;
protected Person(){}
public Person(String nameLast, String nameFirst, Date dob) {
this.nameLast = nameLast;
this.nameFirst = nameFirst;
this.dob = dob;
}
// Getters and Setters...
PersonRepository.java
@Repository
public interface PersonRepository extends JpaRepository<Person, Long>{
}
PersonController.java
@RestController
public class PersonController {
@Autowired
PersonRepository personRepository;
@GetMapping("/person/{id:\\d+}")
public Person getPersonByID(@PathVariable long id){
return personRepository.getOne(id);
}
}
If someone could help me understand why this is not working, it would be very much appreciated. Thanks!
Solution
It turns out this was all caused by me using the wrong method. If I replace return personRepository.getOne(id)
with return personRepository.findOne(id)
, this works perfectly. I don't understand why getOne()
does not work, but this did solve the issue.
Answered By - Adam P