Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@ManyToOne and @BatchSize

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?

like image 821
Łukasz Rzeszotarski Avatar asked Oct 24 '12 11:10

Łukasz Rzeszotarski


2 Answers

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.

like image 98
chris Avatar answered Nov 09 '22 00:11

chris


@ManyToOne associated with @BatchSize could make sense only if the corresponding field is marked as lazy (lazy=true).

Indeed, if the field is not lazy, it's by definition already loaded since the enclosing entity is loaded, so the problem of database calls doesn't apply.

Imagine a Person class who has a collection of ShoesPair element (ShoesPair.class) and within this one is present an owner field marked as lazy (since optional and not really bringing an important information when retrieving a specific pair of shoes).

One wants to iterate through 25 pair of shoes (25 ShoesPair objects) in order to retrieve their owner.

If the owner field (corresponding to one person) is only annotated with @ManyToOne, there would be 25 select to database.

However, if annoted with @BatchSize(size=5), there would be merely 5 calls and so increasing performance.

From the Hibernate documentation, it is precised that batch size does not only apply with collections:

You can also enable batch fetching of collections.

Hibenate mentions especially @OneToMany cases, because these one are applied with fields that are in 90% of cases marked as lazy.

like image 6
Mik378 Avatar answered Nov 09 '22 00:11

Mik378