在 Spring 本机查询项目中获取空值
Getting Null Values in Spring Native Query Project
这是我的数据存储库文件,我使用本机查询来检索数据的所有数据地址(位置)。我使用 Postman 调用了该函数,但得到了位置的空输出。第一次使用Native query 真的无法解决这些错误
DataRepository
public interface DataRepository extends JpaRepository<Data, Long> {
@Query(value = "SELECT dataAddress FROM Data")
List<DataProject> getDataAddress();
}
DataServiceImpl
public List<DataProject> getDataAddress() {
return dataRepository.getDataAddress();
}
数据服务
List<DataProject> getDataAddress();
DataModel
@Entity
@Table(name = "CCCData")
public class Data {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long dataId;
@Column(name = "DATA_NAME")
private String dataName;
@Column(name ="DATA_ADDRESS")
private String dataAddress;
@Column(name = "DATA_DESC")
private String dataDesc;
@CreationTimestamp
private Date dateOfCreated;
@CreationTimestamp
private Date dateOfUpdated;
public long getDataId() {
return dataId;
}
public void setDataId(long dataId) {
this.dataId = dataId;
}
public String getDataName() {
return dataName;
}
public void setDataName(String dataName) {
this.dataName = dataName;
}
public String getDataAddress() {
return dataAddress;
}
public void setDataAddress(String dataAddress) {
this.dataAddress = dataAddress;
}
public String getDataDesc() {
return dataDesc;
}
public void setDataDesc(String dataDesc) {
this.dataDesc = dataDesc;
}
public Date getDateOfCreated() {
return dateOfCreated;
}
public void setDateOfCreated(Date dateOfCreated) {
this.dateOfCreated = dateOfCreated;
}
public Date getDateOfUpdated() {
return dateOfUpdated;
}
public void setDateOfUpdated(Date dateOfUpdated) {
this.dateOfUpdated = dateOfUpdated;
}
DataProjection
public interface DataProject {
String getDataAddress();
}
数据控制器
@GetMapping("/data/locations")
public List<DataProject> getDataAddress() {
return dataService.getDataAddress();
}
邮差输出
[
{
"dataAddress": null
},
{
"dataAddress": null
},
{
"dataAddress": null
},
{
"dataAddress": null
}
]
Spring 不会 return 您只能使用以下查询来解决。它仍然return你DATA
对象
public interface DataRepository extends JpaRepository<Data, Long> {
@Query(value = "SELECT dataAddress FROM Data")
List<DataProject> getDataAddress();
}
为了仅获取 DataAddress
,您需要在 Data
模型中创建一个构造函数,仅用于 DataAddress
public Data(String dataAddress) {
this.dataAddress = dataAddress;
}
您的查询将如下所示:
public interface DataRepository extends JpaRepository<Data, Long> {
@Query(value = "SELECT new Data(dataAddress) FROM Data")
List<DataProject> getDataAddress();
}
更新 1:
如果您需要将此用于具有相同数据类型的其他字段,那么基于 'constructor' 以上的方法将失败。还有一些其他选择:
You can fetch
DATA
object and use java stream map function to extract only 1 field.data.stream().map((data) -> data.getDataAddress()).collect(Collectors.toList())
You can use native SQL query to fetch only required fields.
@Query(value = "SELECT d.data_address FROM CCCData d", nativeQuery=true)