I use eclipselink 2.6.4 and I have the following entities
@Entity
@Table(name = "articles")
public class Article {
@Id
@Column(name = "id")
private Integer id;
@Column(name = "title")
private String title;
@OneToMany(fetch = FetchType.EAGER,mappedBy = "article")
@BatchFetch(BatchFetchType.IN)
private List<Author> authors
//+ setters and getters
}
@Entity
@Table(name = "authors")
public class Author {
@Id
@Column(name = "id")
private Integer id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "articleId")
private Article article;
@Column(name = "surname")
private String surname;
//+setters and getters
}
And this is the code I use to read all articles with their authors:
String queryString="SELECT e FROM Article e";
Query query = em.createQuery(queryString);
query.setHint("eclipselink.batch.type", "IN");
query.setHint("eclipselink.batch", "e.authors");
query.setFirstResult(position);
query.setMaxResults(amount);
List<Article> items=query.getResultList();
In DB I have 3 articles and every article has two authors. And these are the queries eclipse link executes:
SELECT id AS a1, title AS a2 FROM articles LIMIT ? OFFSET ? bind => [2 parameters bound]
SELECT id, surname, articleId FROM authors WHERE (articleId IN (?,?,?)) bind => [3 parameters bound]
SELECT id, title FROM articles WHERE (id IN (?,?)) bind => [2 parameters bound]
SELECT id, surname, articleId FROM authors WHERE (articleId = ?) bind => [1 parameter bound]
SELECT id, surname, articleId FROM authors WHERE (articleId = ?) bind => [1 parameter bound]
Why so many queries? I expect only two queries. What is my mistake?
EDIT
I did two more tests:
- I only used annotation
@BatchFetch(BatchFetchType.IN)
in Article class on field authors (without adding hints to query) I didn't use annotation
@BatchFetch(BatchFetchType.IN)
but used two hints on query:String queryString="SELECT e FROM Article e"; Query query = em.createQuery(queryString); query.setHint("eclipselink.batch.type", "IN"); query.setHint("eclipselink.batch", "e.authors"); query.setFirstResult(0); query.setMaxResults(10); List items=query.getResultList();
The data in table articles:
| id | title |
-----------------
| 1 | article1 |
| 2 | article2 |
| 3 | article3 |
The data in table authors:
| id | articleId | surname |
------------------------------
| 1 | 1 | Author1 |
| 2 | 1 | Author2 |
| 3 | 2 | Author3 |
| 4 | 2 | Author4 |
| 5 | 3 | Author5 |
| 6 | 3 | Author6 |
In each test 6 queries are executed:
SELECT id AS a1, title AS a2 FROM articles LIMIT ? OFFSET ? bind => [2 parameters bound]
SELECT id, surname, articleId FROM authors WHERE (articleId IN (?,?,?)) bind => [3 parameters bound]
SELECT id, title FROM articles WHERE (id = ?) bind => [1 parameter bound]
SELECT id, surname, articleId FROM authors WHERE (articleId = ?) bind => [1 parameter bound]
SELECT id, title FROM articles WHERE (id = ?) bind => [1 parameter bound]
SELECT id, surname, articleId FROM authors WHERE (articleId = ?) bind => [1 parameter bound]