Difference between CrudRepository findOne() and JpaRepository getOne()

后端 未结 3 1510
日久生厌
日久生厌 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 17:14

    Suppose you want to remove an Entity by id. In SQL you can execute a query like this :

    "delete form TABLE_NAME where id = ?". 
    

    And in Hibernate, first you have to get a managed instance of your Entity and then pass it to EntityManager.remove method.

    Entity a = em.find(Entity.class, id);
    em.remove(a);
    

    But this way, You have to fetch the Entity you want to delete from database before deletion. Is that really necessary ?

    The method EntityManager.getReference returns a Hibernate proxy without querying the database and setting the properties of your entity. Unless you try to get properties of the returned proxy yourself.

    Method JpaRepository.getOne uses EntityManager.getReference method instead of EntityManager.find method. so whenever you need a managed object but you don't really need to query database for that, it's better to use JpaRepostory.getOne method to eliminate the unnecessary query.

提交回复
热议问题