【发布时间】:2017-07-11 10:14:36
【问题描述】:
我在下面的例子中使用了 spring boot、spring web 和 spring data。
我有一个名为 Person 的实体,并且我已经在数据库中填充了两个 Persons:
个人实体
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true, nullable = false)
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Personne() {
}
public Personne(long id, String name) {
this.id = id;
this.name = name;
}}
PersonRepository
@Repository
public interface PersonRepository extends JpaRepository<Person, Long> {
}
PersonController
@RestController
public class PersonController {
@Autowired
private PersonRepository personRepo;
@RequestMapping(value = "/perss/{id}")
public Person getById(@PathVariable("id") long id) {
return personRepo.xxxx(id);
}}
用例 1:
当我用 personRepo.getOne(id) 替换 personRepo.xxxx(id) 并点击 localhost:8080/perss/1 时,由于 getOne() 方法,我在浏览器中收到 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) 错误将代理返回到杰克逊以某种方式无法转换的 Person 。
用例 2:
当我将 personRepo.xxxx(id) 替换为 personRepo.findOne(id) 并点击 localhost:8080/perss/1 时,我会以正确的 JSON 格式获得所需的 Person 对象(这个可以正常工作)。
用例 3:
当我将PersonController getById() 方法的代码替换为以下代码时:
@RequestMapping(value = "/perss/{id}")
public Person getById(@PathVariable("id") long id) {
Person p1 = personRepo.findOne(id);
Person p2 = personRepo.getOne(id);
return p2;
}
然后点击localhost:8080/perss/1,我会得到正确 JSON 格式的所需 Person 对象。
问题:
使用getOne() 会出错,但同时使用findOne() 和getOne() 会得到很好的结果。
findOne() 如何影响getOne() 的行为。
编辑
用例 4
当我颠倒 p1 和 p2 的顺序时,我得到一个错误。
@RequestMapping(value = "/perss/{id}")
public Person getById(@PathVariable("id") long id) {
Person p2 = personRepo.getOne(id);
Person p1 = personRepo.findOne(id);
return p2;
}
【问题讨论】:
标签: java hibernate jackson spring-data