@ManyToOne and @BatchSize

Łukasz Rzeszotarski picture Łukasz Rzeszotarski · Oct 24, 2012 · Viewed 16.3k times · Source

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

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

I always thought that @BatchSize annotation only affects when annotated at class level or on a collection (@OneToMany) and affects pre-fetching when iterating.

But maybe I am wrong and annotating @ManyToOne with @BatchSize affects something. I can't find the answer in the documentation.

Does annotating @ManyToOne with @BatchSize have sense?

Answer

chris picture chris · Dec 20, 2013

I think the question refers to combining @ManyToOne and @BatchSize on the same field, e.g.:

@ManyToOne
@BatchSize(size = 5)
private User owner;

This use case is not supported by Hibernate, at least when using annotations. The only uses of batch fetching mentioned by the documentation are:

  • On collection fields, i.e., @OneToMany or @ManyToMany (but not @ManyToOne)
  • On the entity class to be fetched

E.g.:

@Entity
@BatchSize(size = 5)
public class User {
  ...
}

This latter case enables batching for all relationships of type User, including many-to-one relationships. However, with the annotation on the entity class it is not possible to control the behaviour on a field-by-field basis.

A search through the Hibernate source code for all uses of @BatchSize confirms the lack of support for your usage. From what I see in AnnotationBinder.java, the @BatchSize annotation is only inspected on the entity class and on fields which have some kind of @XxxToMany annotation.