JPA 查询部分字段,并返回多行匹配结果
时间: 2023-08-18 21:05:14 浏览: 55
JPA查询部分字段,并返回多行匹配结果,可以使用Spring Data JPA提供的投影(Projection)功能和返回List的方式来实现。
首先,定义一个自定义的接口或DTO对象,定义需要查询的字段。
例如,需要查询用户表中的用户名和邮箱,可以创建一个自定义接口如下:
```
public interface UserProjection {
String getUsername();
String getEmail();
}
```
然后,在Repository接口中定义查询方法,使用`@Query`注解指定查询语句,并在查询语句中使用`SELECT`关键字选择需要查询的字段。
例如,查询用户名和邮箱的方法可以定义如下:
```
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u.username AS username, u.email AS email FROM User u WHERE u.age > :age")
List<UserProjection> findUsernameAndEmailByAge(@Param("age") int age);
}
```
在查询语句中,使用`AS`关键字将查询结果映射到自定义接口中定义的属性中。
最后,在Service层调用Repository中定义的查询方法,获取需要查询的多行字段。
例如,在Controller中调用Service中的方法:
```
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users/{age}")
public List<UserProjection> getUsers(@PathVariable int age) {
return userService.findUsernameAndEmailByAge(age);
}
}
```
这样就可以查询到用户表中指定字段的多行数据了。