使用Spring Data Jpa时,无法直接查询数据表中的部分字段,只能直接查询所有字段,如果有查询部分字段的需求,需在数据表所对应的实体类里增加一个有参构造器,有参构造器的参数为要查询的字段,且顺序需与查询顺序一致。
实体类如下:
@Entity
public class Car{
@Id
@Column(name="id", nullable = false)
private Long id;
@Column
private String price;
@Column
private String color;
@Column
private String brand;
public Car(){}
public Car(String price){
this.price = price;
}
}
Repository如下
public interface CarRepository extends JpaRepository<Car, Long> {
@Query(value = "SELECT price FROM car WHERE id =? ",nativeQuery = true)
String findPriceById(Long id);
}
本文介绍如何使用SpringDataJpa实现对数据库表中特定字段的查询功能。通过在实体类中定义有参构造器并指定所需字段,可以在Repository接口中使用@Query注解执行自定义SQL查询。
5755

被折叠的 条评论
为什么被折叠?



