我的日常开发记录日志
首页
  • Laravel
  • Thinkphp
  • Swoole
  • Workman
  • php
  • HTML
  • CSS
  • JavaScript
  • Vue
  • ES6
  • 小程序
  • Mysql
  • Redis
  • Es
  • MongoDb
  • Git
  • Composer
  • Linux
  • Nginx
  • Docker
  • Vpn
  • 开发实战
  • 开发工具类
  • 友情链接
💖关于
💻收藏
  • 分类
  • 标签
  • 归档数据
GitHub (opens new window)

我的日常开发记录日志

never give up
首页
  • Laravel
  • Thinkphp
  • Swoole
  • Workman
  • php
  • HTML
  • CSS
  • JavaScript
  • Vue
  • ES6
  • 小程序
  • Mysql
  • Redis
  • Es
  • MongoDb
  • Git
  • Composer
  • Linux
  • Nginx
  • Docker
  • Vpn
  • 开发实战
  • 开发工具类
  • 友情链接
💖关于
💻收藏
  • 分类
  • 标签
  • 归档数据
GitHub (opens new window)
  • laravel

  • thinkphp

  • swoole

  • workman

  • php

  • gpt

  • java

    • map和list遍历
    • 基本的类
    • 静态方法和属性
    • java包相关
    • 基础mvc结构
    • 注解理解
    • 泛型
    • 数据库查询
    • 后端
    • java
    窝窝侠
    2024-08-07

    数据库查询

    在 Spring Data JPA 中,可以通过方法查询、Criteria API、JPA Specification 或 Querydsl 来实现类似 Laravel 框架的查询链式调用。尽管没有完全相同的语法,但这些方法可以实现类似的效果。

    # 使用 Criteria API

    Criteria API 可以构建动态查询,并支持链式调用。

    # 1. 添加依赖

    确保你已经在 pom.xml 中添加了 Spring Data JPA 相关的依赖:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    
    1
    2
    3
    4

    # 2. 定义 User 实体类

    假设你已经定义了 User 实体类:

    package com.example.admin.model;
    
    import jakarta.persistence.*;
    
    @Entity
    @Table(name = "base_admins")
    public class User {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
    
        @Column(name = "user_name")
        private String userName;
    
        // Getters and Setters
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31

    # 3. 使用 Criteria API 进行查询

    在 UserService 中使用 Criteria API 进行查询:

    import org.springframework.stereotype.Service;
    import jakarta.persistence.EntityManager;
    import jakarta.persistence.PersistenceContext;
    import jakarta.persistence.criteria.CriteriaBuilder;
    import jakarta.persistence.criteria.CriteriaQuery;
    import jakarta.persistence.criteria.Predicate;
    import jakarta.persistence.criteria.Root;
    
    import java.util.ArrayList;
    import java.util.List;
    
    @Service
    public class UserService {
    
        @PersistenceContext
        private EntityManager entityManager;
    
        public List<User> getUsers(String userName) {
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<User> query = cb.createQuery(User.class);
            Root<User> user = query.from(User.class);
    
            List<Predicate> predicates = new ArrayList<>();
            if (userName != null) {
                predicates.add(cb.equal(user.get("userName"), userName));
            }
    
            query.select(user).where(predicates.toArray(new Predicate[0]));
    
            return entityManager.createQuery(query).getResultList();
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32

    # 4. 在 Controller 中调用

    在 UserController 中调用 UserService:

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.List;
    
    @RestController
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        @GetMapping("/users")
        public ResponseEntity<List<User>> getUsers(@RequestParam(required = false) String userName) {
            List<User> users = userService.getUsers(userName);
            return ResponseEntity.ok(users);
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20

    # 使用 Spring Data JPA 的 Query Methods

    另一种方法是使用 Spring Data JPA 提供的查询方法,这些方法可以通过方法命名规则自动生成 SQL 查询。

    # 1. 定义 UserRepository

    在 UserRepository 中定义查询方法:

    import org.springframework.data.jpa.repository.JpaRepository;
    import java.util.List;
    
    public interface UserRepository extends JpaRepository<User, Long> {
        List<User> findByUserName(String userName);
    }
    
    1
    2
    3
    4
    5
    6

    # 2. 在 Service 中调用

    在 UserService 中调用 UserRepository:

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service
    public class UserService {
    
        @Autowired
        private UserRepository userRepository;
    
        public List<User> getUsers(String userName) {
            if (userName != null) {
                return userRepository.findByUserName(userName);
            } else {
                return userRepository.findAll();
            }
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19

    # 3. 在 Controller 中调用

    在 UserController 中调用 UserService:

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.List;
    
    @RestController
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        @GetMapping("/users")
        public ResponseEntity<List<User>> getUsers(@RequestParam(required = false) String userName) {
            List<User> users = userService.getUsers(userName);
            return ResponseEntity.ok(users);
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20

    # 使用 JPA Specification

    JPA Specification 可以动态构建查询,并支持链式调用。

    # 1. 添加 Specification 依赖

    确保在 pom.xml 中添加了 Spring Data JPA 相关的依赖。

    # 2. 定义 UserSpecification

    定义一个 UserSpecification 类:

    import org.springframework.data.jpa.domain.Specification;
    import com.example.admin.model.User;
    
    public class UserSpecification {
    
        public static Specification<User> hasUserName(String userName) {
            return (root, query, builder) -> builder.equal(root.get("userName"), userName);
        }
    
        public static Specification<User> selectFields() {
            return (root, query, builder) -> {
                query.multiselect(root.get("id"), root.get("userName"));
                return null;
            };
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16

    # 3. 创建 UserRepository

    创建一个 UserRepository,并让其扩展 JpaSpecificationExecutor:

    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
    
    public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
    }
    
    1
    2
    3
    4
    5

    # 4. 在 UserService 中调用

    在 UserService 中使用 Specification 进行查询:

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.data.jpa.domain.Specification;
    
    import java.util.List;
    
    @Service
    public class UserService {
    
        @Autowired
        private UserRepository userRepository;
    
        public List<User> getUsers(String userName) {
            Specification<User> spec = Specification.where(null);
    
            if (userName != null) {
                spec = spec.and(UserSpecification.hasUserName(userName));
            }
    
            spec = spec.and(UserSpecification.selectFields());
    
            return userRepository.findAll(spec);
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24

    # 5. 在 UserController 中调用

    在 UserController 中调用 UserService:

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.List;
    
    @RestController
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        @GetMapping("/users")
        public ResponseEntity<List<User>> getUsers(@RequestParam(required = false) String userName) {
            List<User> users = userService.getUsers(userName);
            return ResponseEntity.ok(users);
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20

    # 总结

    虽然 Spring Data JPA 没有完全等同于 Laravel 的链式查询语法,但通过 Criteria API、Query Methods 和 JPA Specification,可以实现类似的查询功能。选择哪种方法取决于你的具体需求和项目复杂性。

    在线编辑 (opens new window)
    上次更新: 2025/02/25, 18:30:54
    泛型

    ← 泛型

    最近更新
    01
    showprocess用法
    04-29
    02
    vue3中尖括号和冒号的使用细则
    04-29
    03
    sd使用
    02-22
    更多文章>
    🖥️

    © 2025窝窝侠 💌 豫ICP备20005263号-2 🛀 Theme by 💝 Vdoing && 小胖墩er

    • 跟随系统
    • 浅色模式
    • 深色模式
    • 阅读模式
    ×