Difference between FetchType LAZY and EAGER in Java Persistence API?

后端 未结 15 1304
鱼传尺愫
鱼传尺愫 2020-11-22 08:08

I am a newbie to Java Persistence API and Hibernate.

What is the difference between FetchType.LAZY and FetchType.EAGER in Java Persistence API?

15条回答
  •  野性不改
    2020-11-22 08:44

    I want to add this note to what "Kyung Hwan Min" said above.

    Suppose you are using Spring Rest with this simple architect:

    Controller <-> Service <-> Repository

    And you want to return some data to the front-end, if you are using FetchType.LAZY, you will get an exception after you return data to the controller method since the session is closed in the Service so the JSON Mapper Object can't get the data.

    There is three common options to solve this problem, depends on the design, performance and the developer:

    1. The easiest one is to use FetchType.EAGER, So that the session will still alive at the controller method.
    2. Anti-patterns solutions, to make the session live until the execution ends, it is make a huge performance issue in the system.
    3. The best practice is to use FetchType.LAZY with converter method to transfer data from Entity to another data object DTO and send it to controller, so there is no exception if the session closed.

提交回复
热议问题