我只需要使用Hibernate读取MySQL数据库中表中的每一行,并根据它编写一个文件.但是有9000万行,它们非常大.所以看起来以下是合适的:
ScrollableResults results = session.createQuery("SELECT person FROM Person person")
.setReadOnly(true).setCacheable(false).scroll(ScrollMode.FORWARD_ONLY);
while (results.next())
storeInFile(results.get()[0]);
Run Code Online (Sandbox Code Playgroud)
问题是上面将尝试将所有9000万行加载到RAM中,然后再转到while循环...这将使OutOfMemoryError消除我的内存:Java堆空间异常:(.
所以我猜ScrollableResults不是我想要的?处理这个问题的正确方法是什么?我不介意这个while循环需要几天(好吧我不喜欢它).
我想处理这个问题的另一种方法是使用setFirstResult和setMaxResults迭代结果,只使用常规的Hibernate结果而不是ScrollableResults.这感觉就像它效率低下一样,当我在8900万行中调用setFirstResult时,它将开始花费一段可笑的时间......
更新:setFirstResult/setMaxResults不起作用,事实证明需要花费相当长的时间才能达到我所担心的偏移量.这里一定有解决方案!这不是一个很标准的程序吗?我愿意放弃Hibernate并使用JDBC或其他任何东西.
更新2:我提出的解决方案哪个工作正常,不是很好,基本上是以下形式:
select * from person where id > <offset> and <other_conditions> limit 1
Run Code Online (Sandbox Code Playgroud)
由于我有其他条件,即使是索引中的所有条件,它仍然没有我想要的那么快......所以仍然可以提供其他建议..
这是我的用户视图控制器页面:
@RequestMapping(value="/list")
public ModelAndView listOfUsers() {
ModelAndView modelAndView = new ModelAndView("list-of-users");
List<User> users = userService.getUsers();
PagedListHolder<User> pagedListHolder = new PagedListHolder<>(users);
//pagedListHolder.setPageSize(1);
modelAndView.addObject("users", pagedListHolder);
return modelAndView;
}
Run Code Online (Sandbox Code Playgroud)
这是我的JSP页面:
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>List of users</title>
</head>
<body>
<h1>List of users</h1>
<p>Here you can see the list of the users, edit them, remove or update.</p>
<table …
Run Code Online (Sandbox Code Playgroud)