使用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);
}