JPA default fetch type

后端 未结 4 757
小鲜肉
小鲜肉 2021-02-07 03:14

From my understanding @OneToOne and @ManyToOne JPA annotations do an eager fetch. I want these to be lazily loaded in my application, or a

4条回答
  •  别那么骄傲
    2021-02-07 03:31

    JPA Spec assumes that in general most of the applications will require the singleton relations by default be eager, whereas multi value relations by default be lazy. And at least in my own experience, this is generally the desired architecture. This makes sense, since singleton relations require no significant additional performance in JPA layer and DB layer to create a singleton join on foreign key. However, in contradiction to that, multi valued attributes create either N + 1 problem or large cartesian resultsets that get inflates exponentially as the number of elements in collections and number of joins increase when join fetch is used (Although Hibernate specifically cannot handle join fetches on 2+ eager associations).

    Having said that, as for your suggestion, you require a specific (to be honest not completely uncommon) case to be addressed. Now you have a single case but as there are hundreds of cases like that. So to write specifications you need to draw a line between the generalization and granularity.

    If I were in your shoes, if you think this an absolutely useful feature to be added to JPA Specification, I would submit it to the JCP. On the other hand if you get this(, that and that...) addressed in a specific implementation then you end up in so-called vendor-lockin. So I would work an extra hour to set the lazy fetch on @ManyToOne @OneToOne attributes and stay vendor-free, therefore by sticking to the specification if say a new JPA implementation comes along that is over 15x faster then Hibernate (or whatever implementation you use), it would take little to no effort to move your project that new JPA implementation.

提交回复
热议问题