I am using spring boot, spring web and spring data for the following example.
I have one entity called Person and I already populated two Persons in the database:
Person entity
@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);
}}
Use case 1:
When I replace personRepo.xxxx(id) with personRepo.getOne(id) and tap localhost:8080/perss/1 i get 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) error in the browser due to the fact that getOne() method returns a proxy to Person that jackson somehow cannot convert.
Use case 2:
When I replace personRepo.xxxx(id) with personRepo.findOne(id) and tap localhost:8080/perss/1 I get the desired Person object in the correct JSON format (this one works fine).
Use case 3:
When I replace PersonController getById() method's code with the following one:
@RequestMapping(value = "/perss/{id}")
public Person getById(@PathVariable("id") long id) {
Person p1 = personRepo.findOne(id);
Person p2 = personRepo.getOne(id);
return p2;
}
And tap localhost:8080/perss/1 I get the wanted Person object in the correct JSON format.
Question:
Using getOne() got me an error, but using findOne() and getOne() together gave me good result.
How does the findOne() influence the getOne()'s behavior.
EDIT
Use Case 4
When I reverse the order of p1 and p2 i get an error.
@RequestMapping(value = "/perss/{id}")
public Person getById(@PathVariable("id") long id) {
Person p2 = personRepo.getOne(id);
Person p1 = personRepo.findOne(id);
return p2;
}