@ManyToOne and @BatchSize

前端 未结 3 882
谎友^
谎友^ 2020-12-31 16:50

I found in some old code strange thing (at least for me).

The field which is annotated @ManyToOne is also annotated with @BatchSize.

3条回答
  •  误落风尘
    2020-12-31 17:51

    Solving N+1 query problem with Hibernate

    1 Using Criteria queries with fetchMode

    Criteria criteria = session.createCriteria(Customer.class); criteria.setFetchMode("contact", FetchMode.EAGER);

    2 HOL fetch join

    3 @BatchSize

    The @BatchSize annotation can be used to define how many identical associations to populate in a single database query. If the session has 100 customers attached to it and the mapping of the 'contact' collection is annotated with @BatchSize of size n. It means that whenever Hibernate needs to populate a lazy contact collection it checks the session and if it has more customers which their contact collections need to be populated it fetches up to n collections.

    @OneToMany(mappedBy="customer",cascade=CascadeType.ALL, fetch=FetchType.LAZY)
        @BatchSize(size=25)
        private Set contacts = new HashSet();
    

提交回复
热议问题