【发布时间】:2018-07-07 16:53:41
【问题描述】:
我正在尝试使用 Spring Boot 创建一个基本的 REST 服务,该服务返回使用 Hibernate 从数据库创建的 POJO,然后将其转换为 JSON 并返回给 REST 调用。
我可以将常规的非 Hibernate POJO 作为 JSON 返回,但对于 Hibernate 对象,我收到此错误:
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"])
这是我的代码:
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);
}
}
如果有人可以帮助我理解为什么这不起作用,将不胜感激。谢谢!
【问题讨论】:
-
空bean的错误信息,你确定给定ID的那个人还是找到了?
-
您可以从控制器调用 DaoImpl,您可以在其中从 Hibernate 检索列表,然后当您在控制器中获取列表时,您可以使用 GSON 或使用 jackson binder 将其转换为 JSON。跨度>
标签: hibernate spring-boot