部分字段查询
实体类--------编写想要查询字段的构造方法
@Data
@Entity
@NoArgsConstructor
@Table(name = "user_info", schema = "practice01")
public class UserInfo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long customerId;
private String name;
private String company;
private String address;
private String city;
private String state;
private String country;
private String phone;
/**
* jpa查询部分字段构造方法
* @param name
* @param city
*/
public UserInfo(String name, String city){
this.name = name;
this.city = city;
}
}
Repository--------通过select new 构造方法进行查询
public interface UserInfoRepository extends JpaRepository<UserInfo, Long> {
/**
* 测试部分字段查询样例
* @param name name条件
* @return
*/
@Query(value = "select new UserInfo (name,city) from UserInfo where name = ?1")
List<UserInfo> getPart(String name);
}
Service-----------调用repository对应方法
@Service
public class CustomerService {
private final UserInfoRepository userInfoRepository;
public CustomerService(UserInfoRepository userInfoRepository){
this.userInfoRepository = userInfoRepository;
}
/**
* 测试获取部分字段
* @param name 用户名称参数
* @return
*/
public List<UserInfo> getPart(String name){
return userInfoRepository.getPart(name);
}
}
Resource--------调用service方法
@RestController
@RequestMapping("/api")
@Slf4j
public class UserInfoResource {
private final CustomerService customerService;
public UserInfoResource(CustomerService customerService) {
this.customerService = customerService;
}
/**
* jpa测试获取部分字段
* @param name 名称参数
* @return
*/
@GetMapping("/get/{name}")
public List<UserInfo> getUserInfo(@PathVariable("name") String name){
return customerService.getPart(name);
}
}
访问接口-------测试结果