数据库查询
在 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>
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;
}
}
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();
}
}
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);
}
}
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);
}
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();
}
}
}
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);
}
}
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;
};
}
}
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> {
}
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);
}
}
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);
}
}
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
,可以实现类似的查询功能。选择哪种方法取决于你的具体需求和项目复杂性。