gpt4 book ai didi

hibernate - 无法在 Spring Boot REST 中从 Hibernate POJO 返回 JSON

转载 作者:行者123 更新时间:2023-12-04 12:15:35 25 4
gpt4 key购买 nike

我正在尝试使用 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);
}
}

如果有人能帮助我理解为什么这不起作用,我将不胜感激。谢谢!

最佳答案

原来这都是我用错方法造成的。如果我将 return personRepository.getOne(id) 替换为 return personRepository.findOne(id),则效果很好。我不明白为什么 getOne() 不起作用,但这确实解决了问题。

关于hibernate - 无法在 Spring Boot REST 中从 Hibernate POJO 返回 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48493728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com