Spring Data Jpa可以通过使用Java 8 Stream
接口定义
public interface SysUserRepository extends JpaRepository<SysUser, Long> {
/**
* 根据用户名称查找列表
*
* @param userName 用户名称
* @return 列表
*/
List<SysUser> findByUserName(String userName);
// @Query("select u from SysUser u")
Stream<SysUser> readAllBy();
Stream<SysUser> streamAllBy();
}
使用
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private SysUserRepository sysUserRepository;
@GetMapping("/findAll")
@Transactional
public List<SysUser> findAll() {
try (Stream<SysUser> sysUserStream = sysUserRepository.streamAllBy()) {
return sysUserStream.collect(Collectors.toList());
} catch (Exception ex) {
ex.printStackTrace();
return new ArrayList<>();
}
}
}
注意事项
- 必须通过try catch关闭流
- 方法必须有@Transactional注解
评论 (0)