我使用Spring JPA执行所有数据库操作。但是,我不知道如何从Spring JPA的表中选择特定的列?
例如: SELECT projectName FROM projects
我使用Spring JPA执行所有数据库操作。但是,我不知道如何从Spring JPA的表中选择特定的列?
例如: SELECT projectName FROM projects
当前回答
{
"Comments":"Why not using JDBCTemplate",
"Url":"https://www.baeldung.com/spring-jdbc-jdbctemplate"
}
其他回答
你可以更新你的JPARepository,如下所示。
@Query("select u.status from UserLogin u where u.userId = ?1 or u.email = ?1 or u.mobile = ?1")
public UserStatus findByUserIdOrEmailOrMobile(String loginId);
UserStatus为Enum
public enum UserStatus
{
New,
Active,
Deactived,
Suspended,
Locked
}
我不喜欢语法特别(它看起来有点hack…),但这是我能找到的最优雅的解决方案(它在JPA存储库类中使用了自定义JPQL查询):
@Query("select new com.foo.bar.entity.Document(d.docId, d.filename) from Document d where d.filterCol = ?1")
List<Document> findDocumentsForListing(String filterValue);
当然,您只需要为Document提供一个构造函数,该构造函数接受docId和filename作为构造函数参数。
您可以在存储库接口类中应用下面的代码。
Entityname表示您的数据库表名,例如projects。 列表意味着项目是项目中的实体类。
@Query(value="select p from #{#entityName} p where p.id=:projectId and p.projectName=:projectName")
List<Project> findAll(@Param("projectId") int projectId, @Param("projectName") String projectName);
您可以使用来自Spring Data JPA(文档)的投影。在你的例子中,创建接口:
interface ProjectIdAndName{
String getId();
String getName();
}
并将以下方法添加到存储库中
List<ProjectIdAndName> findAll();
Use:
@Query("SELECT e FROM #{#entityName} e where e.userId=:uid")
List<ClienteEnderecoEntity> findInfoByUid(@Param("uid") UUID uid);