Spring Data 2026 高级查询优雅处理复杂数据操作别叫我大神叫我 Alex 就好。今天我们来聊聊 Spring Data 2026 的高级查询特性这是优雅处理复杂数据操作的重要技术。一、Spring Data 概述Spring Data 是 Spring 生态系统中的重要组件它提供了一种统一的方式来访问各种数据存储。Spring Data 2026 进一步增强了查询能力提供了更多的高级查询特性。核心优势简化数据访问减少样板代码提高开发效率统一 API为不同的数据存储提供统一的访问方式高级查询支持复杂的查询操作性能优化提供查询性能优化的能力事务管理集成事务管理缓存支持集成缓存机制审计功能支持数据审计二、基础查询方法1. 方法命名查询public interface UserRepository extends JpaRepositoryUser, Long { // 根据用户名查询用户 User findByUsername(String username); // 根据邮箱查询用户 User findByEmail(String email); // 根据用户名和密码查询用户 User findByUsernameAndPassword(String username, String password); // 根据年龄范围查询用户 ListUser findByAgeBetween(int minAge, int maxAge); // 根据用户名模糊查询 ListUser findByUsernameLike(String username); // 根据状态查询用户并排序 ListUser findByStatusOrderByCreatedAtDesc(String status); }2. Query 注解public interface UserRepository extends JpaRepositoryUser, Long { // 使用 JPQL 查询 Query(SELECT u FROM User u WHERE u.username :username) User findByUsername(Param(username) String username); // 使用原生 SQL 查询 Query(value SELECT * FROM users WHERE email :email, nativeQuery true) User findByEmail(Param(email) String email); // 复杂查询 Query(SELECT u FROM User u WHERE u.age :age AND u.status :status) ListUser findByAgeGreaterThanAndStatus(Param(age) int age, Param(status) String status); }3. 分页查询public interface UserRepository extends JpaRepositoryUser, Long { // 分页查询 PageUser findByStatus(String status, Pageable pageable); // 分页和排序 PageUser findByAgeGreaterThan(int age, Pageable pageable); } // 使用示例 Pageable pageable PageRequest.of(0, 10, Sort.by(createdAt).descending()); PageUser users userRepository.findByStatus(ACTIVE, pageable);三、高级查询特性1. 动态查询1.1 使用 Specificationpublic interface UserRepository extends JpaRepositoryUser, Long, JpaSpecificationExecutorUser { } // 使用示例 public class UserSpecifications { public static SpecificationUser hasUsername(String username) { return (root, query, criteriaBuilder) - { if (username null) { return null; } return criteriaBuilder.like(root.get(username), % username %); }; } public static SpecificationUser hasAgeGreaterThan(int age) { return (root, query, criteriaBuilder) - { return criteriaBuilder.greaterThan(root.get(age), age); }; } public static SpecificationUser hasStatus(String status) { return (root, query, criteriaBuilder) - { if (status null) { return null; } return criteriaBuilder.equal(root.get(status), status); }; } } // 组合查询 SpecificationUser spec Specification.where(UserSpecifications.hasUsername(alex)) .and(UserSpecifications.hasAgeGreaterThan(18)) .and(UserSpecifications.hasStatus(ACTIVE)); ListUser users userRepository.findAll(spec);1.2 使用 QueryDSL// 配置 QueryDSL dependency groupIdcom.querydsl/groupId artifactIdquerydsl-jpa/artifactId /dependency dependency groupIdcom.querydsl/groupId artifactIdquerydsl-apt/artifactId scopeprovided/scope /dependency // 生成 Q 类 // mvn compile // 使用示例 public interface UserRepository extends JpaRepositoryUser, Long, QuerydslPredicateExecutorUser { } // 创建查询 QUser qUser QUser.user; Predicate predicate qUser.username.contains(alex) .and(qUser.age.gt(18)) .and(qUser.status.eq(ACTIVE)); ListUser users userRepository.findAll(predicate); // 分页查询 Pageable pageable PageRequest.of(0, 10); PageUser userPage userRepository.findAll(predicate, pageable);2. 复杂关联查询2.1 一对一关联Entity public class User { Id GeneratedValue(strategy GenerationType.IDENTITY) private Long id; private String username; private String email; OneToOne(cascade CascadeType.ALL) JoinColumn(name profile_id) private UserProfile profile; // getters and setters } Entity public class UserProfile { Id GeneratedValue(strategy GenerationType.IDENTITY) private Long id; private String firstName; private String lastName; private String address; OneToOne(mappedBy profile) private User user; // getters and setters } public interface UserRepository extends JpaRepositoryUser, Long { // 关联查询 Query(SELECT u FROM User u JOIN FETCH u.profile WHERE u.username :username) User findByUsernameWithProfile(Param(username) String username); }2.2 一对多关联Entity public class User { Id GeneratedValue(strategy GenerationType.IDENTITY) private Long id; private String username; OneToMany(mappedBy user, cascade CascadeType.ALL) private ListOrder orders; // getters and setters } Entity public class Order { Id GeneratedValue(strategy GenerationType.IDENTITY) private Long id; private String orderNumber; private BigDecimal amount; ManyToOne JoinColumn(name user_id) private User user; // getters and setters } public interface UserRepository extends JpaRepositoryUser, Long { // 关联查询 Query(SELECT u FROM User u JOIN FETCH u.orders WHERE u.id :id) User findByIdWithOrders(Param(id) Long id); // 复杂关联查询 Query(SELECT u FROM User u JOIN u.orders o WHERE o.amount :amount) ListUser findByOrdersAmountGreaterThan(Param(amount) BigDecimal amount); }2.3 多对多关联Entity public class User { Id GeneratedValue(strategy GenerationType.IDENTITY) private Long id; private String username; ManyToMany JoinTable( name user_roles, joinColumns JoinColumn(name user_id), inverseJoinColumns JoinColumn(name role_id) ) private SetRole roles; // getters and setters } Entity public class Role { Id GeneratedValue(strategy GenerationType.IDENTITY) private Long id; private String name; ManyToMany(mappedBy roles) private SetUser users; // getters and setters } public interface UserRepository extends JpaRepositoryUser, Long { // 关联查询 Query(SELECT u FROM User u JOIN FETCH u.roles WHERE u.username :username) User findByUsernameWithRoles(Param(username) String username); // 复杂关联查询 Query(SELECT u FROM User u JOIN u.roles r WHERE r.name :roleName) ListUser findByRoleName(Param(roleName) String roleName); }3. 投影查询3.1 接口投影public interface UserProjection { String getUsername(); String getEmail(); } public interface UserRepository extends JpaRepositoryUser, Long { // 投影查询 ListUserProjection findByStatus(String status); // 分页投影查询 PageUserProjection findByAgeGreaterThan(int age, Pageable pageable); }3.2 类投影public class UserDto { private String username; private String email; public UserDto(String username, String email) { this.username username; this.email email; } // getters } public interface UserRepository extends JpaRepositoryUser, Long { // 类投影查询 Query(SELECT new com.example.dto.UserDto(u.username, u.email) FROM User u WHERE u.status :status) ListUserDto findByStatus(Param(status) String status); }3.3 动态投影public interface UserRepository extends JpaRepositoryUser, Long { // 动态投影 T ListT findByStatus(String status, ClassT type); // 动态投影分页 T PageT findByAgeGreaterThan(int age, Pageable pageable, ClassT type); } // 使用示例 ListUserProjection projections userRepository.findByStatus(ACTIVE, UserProjection.class); ListUserDto dtos userRepository.findByStatus(ACTIVE, UserDto.class);四、性能优化1. 批量操作public interface UserRepository extends JpaRepositoryUser, Long { // 批量保存 S extends User ListS saveAll(IterableS entities); // 批量删除 void deleteAllInBatch(); void deleteInBatch(IterableUser entities); } // 使用示例 ListUser users // 准备用户列表 userRepository.saveAll(users); // 批量删除 ListUser usersToDelete // 准备要删除的用户列表 userRepository.deleteInBatch(usersToDelete);2. 缓存优化EnableCaching Configuration public class CacheConfig { Bean public CacheManager cacheManager() { SimpleCacheManager cacheManager new SimpleCacheManager(); cacheManager.setCaches(Arrays.asList( new ConcurrentMapCache(users), new ConcurrentMapCache(orders) )); return cacheManager; } } Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository userRepository; } Cacheable(value users, key #id) public User getUserById(Long id) { return userRepository.findById(id).orElse(null); } CachePut(value users, key #user.id) public User saveUser(User user) { return userRepository.save(user); } CacheEvict(value users, key #id) public void deleteUser(Long id) { userRepository.deleteById(id); } }3. 查询优化3.1 使用索引Entity public class User { Id GeneratedValue(strategy GenerationType.IDENTITY) private Long id; Index(name idx_username) private String username; Index(name idx_email) private String email; // 其他字段 }3.2 避免 N1 查询// 不好的做法 ListUser users userRepository.findAll(); for (User user : users) { ListOrder orders user.getOrders(); // 每次都会执行查询 } // 好的做法 Query(SELECT u FROM User u JOIN FETCH u.orders) ListUser findAllWithOrders(); ListUser users userRepository.findAllWithOrders(); for (User user : users) { ListOrder orders user.getOrders(); // 不会执行额外查询 }3.3 使用分页和限制// 不好的做法 ListUser users userRepository.findAll(); // 可能返回大量数据 // 好的做法 Pageable pageable PageRequest.of(0, 10); PageUser userPage userRepository.findAll(pageable); ListUser users userPage.getContent(); // 限制结果数量 ListUser topUsers userRepository.findTop10ByOrderByCreatedAtDesc();五、事务管理1. 声明式事务Service public class UserService { private final UserRepository userRepository; private final OrderRepository orderRepository; public UserService(UserRepository userRepository, OrderRepository orderRepository) { this.userRepository userRepository; this.orderRepository orderRepository; } Transactional public User createUserWithOrder(User user, Order order) { User savedUser userRepository.save(user); order.setUser(savedUser); orderRepository.save(order); return savedUser; } Transactional(readOnly true) public User getUserWithOrders(Long id) { return userRepository.findByIdWithOrders(id); } }2. 事务传播Service public class OrderService { private final OrderRepository orderRepository; private final PaymentService paymentService; public OrderService(OrderRepository orderRepository, PaymentService paymentService) { this.orderRepository orderRepository; this.paymentService paymentService; } Transactional public Order createOrder(Order order) { Order savedOrder orderRepository.save(order); // 调用其他服务的事务方法 paymentService.processPayment(savedOrder); return savedOrder; } } Service public class PaymentService { private final PaymentRepository paymentRepository; public PaymentService(PaymentRepository paymentRepository) { this.paymentRepository paymentRepository; } Transactional(propagation Propagation.REQUIRES_NEW) public Payment processPayment(Order order) { Payment payment new Payment(); payment.setOrder(order); payment.setAmount(order.getAmount()); payment.setStatus(PENDING); return paymentRepository.save(payment); } }六、审计功能1. 启用审计Configuration EnableJpaAuditing public class JpaConfig { } Entity EntityListeners(AuditingEntityListener.class) public class User { Id GeneratedValue(strategy GenerationType.IDENTITY) private Long id; private String username; CreatedBy private String createdBy; CreatedDate private LocalDateTime createdAt; LastModifiedBy private String lastModifiedBy; LastModifiedDate private LocalDateTime lastModifiedAt; // getters and setters }2. 自定义审计Component public class CustomAuditorAware implements AuditorAwareString { Override public OptionalString getCurrentAuditor() { // 从 SecurityContext 中获取当前用户 Authentication authentication SecurityContextHolder.getContext().getAuthentication(); if (authentication ! null authentication.isAuthenticated()) { return Optional.of(authentication.getName()); } return Optional.of(system); } } Configuration EnableJpaAuditing(auditorAwareRef customAuditorAware) public class JpaConfig { }七、实践案例电商平台数据访问场景描述构建一个电商平台包含用户、订单、产品、支付等数据模型需要实现复杂的数据访问操作。实现方案1. 数据模型用户模型Entity EntityListeners(AuditingEntityListener.class) public class User { Id GeneratedValue(strategy GenerationType.IDENTITY) private Long id; Index(name idx_username) private String username; Index(name idx_email) private String email; private String password; private String status; OneToMany(mappedBy user, cascade CascadeType.ALL) private ListOrder orders; ManyToMany JoinTable( name user_roles, joinColumns JoinColumn(name user_id), inverseJoinColumns JoinColumn(name role_id) ) private SetRole roles; CreatedBy private String createdBy; CreatedDate private LocalDateTime createdAt; LastModifiedBy private String lastModifiedBy; LastModifiedDate private LocalDateTime lastModifiedAt; // getters and setters }订单模型Entity public class Order { Id GeneratedValue(strategy GenerationType.IDENTITY) private Long id; private String orderNumber; private BigDecimal amount; private String status; ManyToOne JoinColumn(name user_id) private User user; OneToMany(mappedBy order, cascade CascadeType.ALL) private ListOrderItem items; OneToOne(mappedBy order, cascade CascadeType.ALL) private Payment payment; // getters and setters }产品模型Entity public class Product { Id GeneratedValue(strategy GenerationType.IDENTITY) private Long id; private String name; private String description; private BigDecimal price; private int stock; OneToMany(mappedBy product, cascade CascadeType.ALL) private ListOrderItem items; // getters and setters }2. 仓库接口用户仓库public interface UserRepository extends JpaRepositoryUser, Long, JpaSpecificationExecutorUser { User findByUsername(String username); User findByEmail(String email); Query(SELECT u FROM User u JOIN FETCH u.orders WHERE u.id :id) User findByIdWithOrders(Param(id) Long id); Query(SELECT u FROM User u JOIN FETCH u.roles WHERE u.username :username) User findByUsernameWithRoles(Param(username) String username); ListUser findByStatus(String status); PageUser findByAgeGreaterThan(int age, Pageable pageable); }订单仓库public interface OrderRepository extends JpaRepositoryOrder, Long { Query(SELECT o FROM Order o JOIN FETCH o.items JOIN FETCH o.payment WHERE o.id :id) Order findByIdWithItemsAndPayment(Param(id) Long id); ListOrder findByUserId(Long userId); PageOrder findByStatus(String status, Pageable pageable); Query(SELECT o FROM Order o WHERE o.user.username :username) ListOrder findByUsername(Param(username) String username); }产品仓库public interface ProductRepository extends JpaRepositoryProduct, Long { ListProduct findByNameContaining(String name); ListProduct findByPriceBetween(BigDecimal minPrice, BigDecimal maxPrice); ListProduct findByStockGreaterThan(int stock); Query(SELECT p FROM Product p WHERE p.price :price AND p.stock 0) ListProduct findAvailableProducts(Param(price) BigDecimal price); }3. 服务实现用户服务Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository userRepository; } Transactional public User createUser(User user) { return userRepository.save(user); } Transactional(readOnly true) public User getUserById(Long id) { return userRepository.findById(id).orElse(null); } Transactional(readOnly true) public User getUserWithOrders(Long id) { return userRepository.findByIdWithOrders(id); } Transactional(readOnly true) public ListUser getUsersByStatus(String status) { return userRepository.findByStatus(status); } Transactional(readOnly true) public PageUser getUsersByAge(int age, Pageable pageable) { return userRepository.findByAgeGreaterThan(age, pageable); } }订单服务Service public class OrderService { private final OrderRepository orderRepository; private final UserRepository userRepository; private final ProductRepository productRepository; public OrderService(OrderRepository orderRepository, UserRepository userRepository, ProductRepository productRepository) { this.orderRepository orderRepository; this.userRepository userRepository; this.productRepository productRepository; } Transactional public Order createOrder(Long userId, ListOrderItemRequest items) { User user userRepository.findById(userId).orElseThrow(() - new RuntimeException(User not found)); Order order new Order(); order.setUser(user); order.setOrderNumber(generateOrderNumber()); order.setStatus(PENDING); BigDecimal totalAmount BigDecimal.ZERO; ListOrderItem orderItems new ArrayList(); for (OrderItemRequest itemRequest : items) { Product product productRepository.findById(itemRequest.getProductId()) .orElseThrow(() - new RuntimeException(Product not found)); if (product.getStock() itemRequest.getQuantity()) { throw new RuntimeException(Insufficient stock for product: product.getName()); } OrderItem orderItem new OrderItem(); orderItem.setOrder(order); orderItem.setProduct(product); orderItem.setQuantity(itemRequest.getQuantity()); orderItem.setPrice(product.getPrice()); orderItems.add(orderItem); totalAmount totalAmount.add(product.getPrice().multiply(BigDecimal.valueOf(itemRequest.getQuantity()))); // 减少库存 product.setStock(product.getStock() - itemRequest.getQuantity()); productRepository.save(product); } order.setItems(orderItems); order.setAmount(totalAmount); return orderRepository.save(order); } private String generateOrderNumber() { return ORD System.currentTimeMillis(); } }八、最佳实践1. 仓库设计单一职责每个仓库只负责一个实体的操作方法命名使用清晰的方法命名遵循 Spring Data 的命名规范查询优化合理使用 Query 注解和 JPQL分页处理对于可能返回大量数据的查询使用分页关联查询合理使用 JOIN FETCH 避免 N1 查询2. 服务层设计事务管理合理使用 Transactional 注解业务逻辑将业务逻辑放在服务层仓库只负责数据访问异常处理在服务层处理异常提供友好的错误信息缓存策略合理使用缓存提高性能审计功能启用审计跟踪数据变更3. 性能优化索引设计为频繁查询的字段创建索引批量操作使用批量操作减少数据库交互查询限制使用 LIMIT 和分页避免返回大量数据避免 N1使用 JOIN FETCH 或批量加载缓存使用合理使用缓存减少数据库查询4. 安全性参数绑定使用参数绑定避免 SQL 注入权限控制在服务层实现权限控制数据验证在服务层进行数据验证密码加密对敏感数据进行加密存储5. 测试单元测试测试仓库方法集成测试测试服务层和仓库的集成性能测试测试查询性能边界测试测试边界情况九、总结与建议Spring Data 2026 的高级查询特性为我们提供了强大的数据访问能力。通过合理使用这些特性我们可以简化数据访问减少样板代码提高开发效率处理复杂查询支持复杂的关联查询和动态查询提高性能通过缓存、索引、批量操作等手段提高性能确保数据安全支持事务管理和审计功能提高代码质量使用统一的 API提高代码可读性和可维护性这其实可以更优雅一点通过合理使用 Spring Data 2026 的高级查询特性我们可以构建出更高效、更可靠的数据访问层。别叫我大神叫我 Alex 就好。希望这篇文章能帮助你更好地理解和使用 Spring Data 2026 的高级查询特性。欢迎在评论区分享你的使用经验