【发布时间】:2017-05-15 21:39:36
【问题描述】:
我使用 eclipselink 2.6.4 并且我有以下实体
@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
}
这是我用来和作者一起阅读所有文章的代码:
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();
在 DB 中,我有 3 篇文章,每篇文章都有两位作者。这些是 eclipse 链接执行的查询:
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]
为什么有这么多查询?我希望只有两个查询。我的错误是什么?
编辑
我又做了两个测试:
- 我只在字段作者的文章类中使用注释
@BatchFetch(BatchFetchType.IN)(未添加查询提示) -
我没有使用注解
@BatchFetch(BatchFetchType.IN),而是在查询中使用了两个提示:String queryString="SELECT e FROM Article e"; 查询查询 = em.createQuery(queryString); query.setHint("eclipselink.batch.type", "IN"); query.setHint("eclipselink.batch", "e.authors"); query.setFirstResult(0); query.setMaxResults(10); 列表项=query.getResultList();
表格文章中的数据:
| id | title |
-----------------
| 1 | article1 |
| 2 | article2 |
| 3 | article3 |
表作者中的数据:
| id | articleId | surname |
------------------------------
| 1 | 1 | Author1 |
| 2 | 1 | Author2 |
| 3 | 2 | Author3 |
| 4 | 2 | Author4 |
| 5 | 3 | Author5 |
| 6 | 3 | Author6 |
在每个测试中执行 6 个查询:
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]
【问题讨论】:
标签: java sql jpa eclipselink