我使用与WebSphere 8.5捆绑在一起的OpenJPA 2.3,我必须从表中读取大量数据。我还必须获取与根实体的很多关系。OpenJPA Eager Fetching
大气压我使用的是标准的API来创建搜索查询和选择的实体。我用EAGER注释了所有集合。当我检查日志文件时,它会创建5个查询来获取所有的孩子。这是我想要的方式。 问题在于我必须经过1000次匹配实体之后的选择和停止后才能在java中进行大量筛选。所以我想我指定了读取大小,并立即停止从数据库读取实体,只要我有我的1k结果。
如果我介绍FetchBatchSize设置,OpenJPA的每个实体加载儿童创造单查询。 (N + 1个问题)
我也试图直接在我的查询使用fetch联接语法,但没有成功。那么我做错了什么?
我尝试:
1)
query.setHint("openjpa.FetchPlan.FetchBatchSize", 1000);
query.setHint("openjpa.FetchPlan.ResultSetType", "SCROLL_INSENSITIVE");
2)
OpenJPAQuery<?> kq = OpenJPAPersistence.cast(query);
JDBCFetchPlan fetch = (JDBCFetchPlan) kq.getFetchPlan();
fetch.setFetchBatchSize(1000);
fetch.setResultSetType(ResultSetType.FORWARD_ONLY);
fetch.setFetchDirection(FetchDirection.FORWARD);
fetch.setLRSSizeAlgorithm(LRSSizeAlgorithm.UNKNOWN);
实体:
@Entity
@Table(name = "CONTRACT")
public class Contract {
// omitted the other properties. The other relationships are annotated the same way
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "contract")
private List<Vehicle> vehicles= new ArrayList<Vehicle>();
查询:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Contract> crit = cb.createQuery(Contract.class);
crit.distinct(true);
Root<Contract> r = crit.from(Contract.class);
// omited the where clause. In worst case I have a full table scan without any where clause. (the reason I need the batch size)
Fetch<Contract, Vehicle> fetchVehicles = r.fetch("vehicles", JoinType.LEFT); // I tried to work with a fetch join as well
TypedQuery<Contract> query = em.createQuery(crit);
// query.setHint("openjpa.FetchPlan.FetchBatchSize", FETCH_SIZE);
// query.setHint("openjpa.FetchPlan.ResultSetType", "SCROLL_INSENSITIVE");
OpenJPAQuery<?> kq = OpenJPAPersistence.cast(query);
JDBCFetchPlan fetch = (JDBCFetchPlan) kq.getFetchPlan();
fetch.setFetchBatchSize(FETCH_SIZE);
fetch.setResultSetType(ResultSetType.FORWARD_ONLY);
fetch.setFetchDirection(FetchDirection.FORWARD);
fetch.setLRSSizeAlgorithm(LRSSizeAlgorithm.UNKNOWN);
fetch.setEagerFetchMode(FetchMode.PARALLEL);
List<TPV> queryResult = query.getResultList();
// here begins the filtering and I stop as soon I have 1000 results
感谢您的帮助!
你使用JPA注释的实体吗?如果是这样,你可以添加相关实体吗? – thobens
是的,我愿意。在一分钟之内发布它。 – mkuff
我展示了一个关系的例子,当我玩弄批量大小时,它不再渴望加载。 – mkuff