spring data jpa使用流式查询

2023-03-08 14:39:50 浏览数 (3)

思路

调用org.hibernate.query.Query.stream方法查询数据

代码样例

代码语言:javascript复制
import static org.hibernate.annotations.QueryHints.READ_ONLY;
import static org.hibernate.jpa.QueryHints.HINT_FETCH_SIZE;
import org.hibernate.query.Query;
  1. 使用HQL查询
代码语言:javascript复制
Query<MyEntity> q = entityManager.createQuery(
	"select e from MyEntity e where field1 = :field1",
	MyEntity.class
)
.setParameter("field1", "test")
.setHint(HINT_FETCH_SIZE, Integer.MIN_VALUE) // 根据数据库实现设置,这里是MYSQL
.setHint(READ_ONLY, true)
.unwrap(Query.class);
Stream<MyEntity> stream= q.stream();
stream.close(); // 释放
  1. 使用动态查询
代码语言:javascript复制
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<MyEntity> query = builder.createQuery(MyEntity.class);
Root<MyEntity> root = query.from(MyEntity.class);
query.where(builder .equal(root.get("field1"), "test"));
query.select(root);
Query<MyEntity> q = entityManager.createQuery(query)
	.setHint(HINT_FETCH_SIZE, Integer.MIN_VALUE)
	.setHint(READ_ONLY, true)
	.unwrap(Query.class);  
Stream<MyEntity> stream= q.stream();
stream.close(); // 释放

直接使用jdbc

代码语言:javascript复制
jdbcTemplate.query(con -> {
    String sql = "select * from t_my_entity where fd_field1 = ?";
    PreparedStatement preparedStatement = this.createPreparedStatement(con, sql, context);
    statement.setString(1, "test");
    statement.setFetchSize(Integer.MIN_VALUE);
    statement.setFetchDirection(ResultSet.FETCH_FORWARD);
    return preparedStatement;
}, resultSet -> {
    // 遍历处理结果
});

0 人点赞