百万级数据下Hibernate关联表高效查询方案咨询
现有Books和Authors两张百万级数据量的表,我对数据库表及Hibernate最佳实践经验不足。已知查询全量Books时需采用批量查询,代码如下:
int offset = 0; while (true) { Query<Book> query = session.createQuery("FROM Book", Book.class); query.setFirstResult(offset); query.setMaxResults(BATCH_SIZE); List<Book> books = query.list(); if (books.isEmpty()) { break; } // 处理批量图书数据 processBatch(books); // 清理session释放内存 session.clear(); offset += BATCH_SIZE; }
Books与Authors为多对一关联,我需要获取每本图书对应的Author表字段(如email),但Authors表数据量庞大,不确定如何高效实现,以下是我尝试过的方法及考虑的方案:
- HQL关联抓取:使用
session.createQuery("from Book bk left join fetch bk.author"),但担心即使批量查询Books,仍会引发内存问题。 - 原生SQL关联查询:使用
session.createSQLQuery('select * from books left join authors on books.author_id = authors.id'),在Books数据量较小时速度快,但会丢失ORM自动映射实体的特性。
我考虑采用Stack Overflow上的方案:在Book实体中同时映射author_id字段和Author关联对象,代码如下:
@Column(name="author_id", updatable=false, insertable=false) public Long authorId; @ManyToOne public Author author;
查询步骤为先批量查询Books获取所有author_id,再批量查询对应的Author数据:
// 用之前的批量方式查询Book,结果存入booksList List<Long> authorIds = new ArrayList<>(); for(Book book : booksList) { authorIds.add( book.getAuthorId() ); // 这样不会触发额外的Hibernate查询,对比调用book.getAuthor().getId()的方式 } session.createQuery("from Author where id in (:authorIds)").setParameterList("authorIds", authorIds); // 这里是否也需要批量处理?
请问该方案是否为最优解?或有无更优方案?另外,SQL层面已建立外键关联:
Create table Books ( ... author_id int NOT NULL, FOREIGN KEY (author_id) REFERENCES authors(id) );
内容的提问来源于stack exchange,提问作者Cindy
相关产品推荐
相关产品推荐

