我使用Spring JPA执行所有数据库操作。但是,我不知道如何从Spring JPA的表中选择特定的列?

例如: SELECT projectName FROM projects


当前回答

使用本机查询:

Query query = entityManager.createNativeQuery("SELECT projectId, projectName FROM projects");
List result = query.getResultList();

其他回答

在本地sql中可以指定null作为字段值。

@Query(value = "select p.id, p.uid, p.title, null as documentation, p.ptype " +
            " from projects p " +
            "where p.uid = (:uid)" +
            "  and p.ptype = 'P'", nativeQuery = true)
Project findInfoByUid(@Param("uid") String uid);

我不喜欢语法特别(它看起来有点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作为构造函数参数。

使用本机查询:

Query query = entityManager.createNativeQuery("SELECT projectId, projectName FROM projects");
List result = query.getResultList();

在我看来,这是一个很好的解决方案:

interface PersonRepository extends Repository<Person, UUID> {

    <T> Collection<T> findByLastname(String lastname, Class<T> type);
}

像这样使用它

void someMethod(PersonRepository people) {

  Collection<Person> aggregates =
    people.findByLastname("Matthews", Person.class);

  Collection<NamesOnly> aggregates =
    people.findByLastname("Matthews", NamesOnly.class);
}

我想最简单的方法可能是使用Spring-Data附带的QueryDSL。

对于你的问题,答案可以是

JPAQuery query = new JPAQuery(entityManager);
List<Tuple> result = query.from(projects).list(project.projectId, project.projectName);
for (Tuple row : result) {
 System.out.println("project ID " + row.get(project.projectId));
 System.out.println("project Name " + row.get(project.projectName)); 
}}

实体管理器可以自动连接,你总是会使用对象和类,而不使用*QL语言。

正如您在链接中看到的,对我来说,最后一种选择似乎更优雅,即使用DTO存储结果。应用到你的例子将是:

JPAQuery query = new JPAQuery(entityManager);
QProject project = QProject.project;
List<ProjectDTO> dtos = query.from(project).list(new QProjectDTO(project.projectId, project.projectName));

定义ProjectDTO为:

class ProjectDTO {

 private long id;
 private String name;
 @QueryProjection
 public ProjectDTO(long projectId, String projectName){
   this.id = projectId;
   this.name = projectName;
 }
 public String getProjectId(){ ... }
 public String getProjectName(){....}
}