Difference between CrudRepository findOne() and JpaRepository getOne()

后端 未结 3 1497
日久生厌
日久生厌 2021-01-02 16:40

I read that getOne() is lazy loaded and findOne() fetches the whole entity right away. I\'ve checked the debugging log and I even enabled monitorin

3条回答
  •  醉梦人生
    2021-01-02 16:52

    It is just a guess but in 'pure JPA' there is a method of EntityManager called getReference. And it is designed to retrieve entity with only ID in it. Its use was mostly for indicating reference existed without the need to retrieve whole entity. Maybe the code will tell more:

    // em is EntityManager
    Department dept = em.getReference(Department.class, 30);  // Gets only     entity with ID property, rest is null
    Employee emp = new Employee();
    emp.setId(53);
    emp.setName("Peter");
    emp.setDepartment(dept);
    dept.getEmployees().add(emp);
    em.persist(emp);
    

    I assume then getOne serves the same purpose. Why the queries generated are the same you ask? Well, AFAIR in JPA bible - Pro JPA2 by Mike Keith and Merrick Schincariol - almost every paragraph contains something like 'the behaviour depends on the vendor'.

    EDIT:

    I've set my own setup. Finally I came to conclusion that if You in any way interfere with entity fetched with getOne (even go for entity.getId()) it causes SQL to be executed. Although if You are using it only to create proxy (eg. for relationship indicator like shown in a code above), nothing happens and there is no additional SQL executed. So I assume in your service class You do something with this entity (use getter, log something) and that is why the output of these two methods looks the same.

    ChlebikGitHub with example code
    SO helpful question #1
    SO helpful question #2

提交回复
热议问题