Ada*_*m P 3 hibernate spring-boot
我正在尝试使用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"])
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
人.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...
Run Code Online (Sandbox Code Playgroud)
PersonRepository.java
@Repository
public interface PersonRepository extends JpaRepository<Person, Long>{
}
Run Code Online (Sandbox Code Playgroud)
PersonController.java
@RestController
public class PersonController {
@Autowired
PersonRepository personRepository;
@GetMapping("/person/{id:\\d+}")
public Person getPersonByID(@PathVariable long id){
return personRepository.getOne(id);
}
}
Run Code Online (Sandbox Code Playgroud)
如果有人可以帮助我理解为什么它不起作用,将不胜感激。谢谢!
事实证明,这都是我使用错误方法造成的。如果我替换return personRepository.getOne(id)为return personRepository.findOne(id),这将完美地工作。我不明白为什么getOne()不起作用,但这确实解决了问题。
| 归档时间: |
|
| 查看次数: |
2224 次 |
| 最近记录: |