Spring Boot JpaRepository:不使用@Query返回字符串

mwyxok5s  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(86)

在存储库中,我可以使用以下代码来检索字符串形式的名称:

@Query("SELECT q.contractorName FROM Quotations q WHERE q.id = :id")
String findContractorNameById(@Param("id") Long id);

字符串
这很好,但是对于这样一个简单的事情,我只是想知道它需要@Query注解做什么。我试着在没有它的情况下做同样的事情:

String findContractorNameById(Long id);


我得到警告:
此处需要“Quotations”域类型或有效的投影接口
例外情况:
org.hibernate.query.QueryTypeMismatchException:指定的结果类型[java.lang.String]与查询选择类型不匹配-多个选择:使用元组或数组
由于ID是唯一的,所以我只需要一个String,而不是Tuple或Array。
不使用@Query可以吗?

gudnpqoy

gudnpqoy1#

是的,这是可能的。
你可能有一个这样的Quotation对象。

@Entity
public class Quotation {

    ...
    private String contractorName;
    ...
}

字符串
为此,可以按如下方式创建投影。

interface ContractorNameOnly {

    String getContractorName();
}


您可以在存储库中实现此功能,如下所示。

interface QuotationRepository {

    ContractorNameOnly findContractorNameById(Long id);
}


如需了解更多信息,请查看Spring Projections page

相关问题