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

例如: SELECT projectName FROM projects


当前回答

使用本机查询:

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

其他回答

在我的情况下,我创建了一个单独的实体类,没有字段是不需要的(只有字段是必需的)。

将实体映射到同一个表。 现在当所有的列都是必需的,我使用旧的实体,当只有一些列是必需的,我使用lite实体。

如。

@Entity
@Table(name = "user")
Class User{
         @Column(name = "id", unique=true, nullable=false)
         int id;
         @Column(name = "name", nullable=false)
         String name;
         @Column(name = "address", nullable=false)
         Address address;
}

你可以创建如下内容:

@Entity
@Table(name = "user")
Class UserLite{
         @Column(name = "id", unique=true, nullable=false)
         int id;
         @Column(name = "name", nullable=false)
         String name;
}

当您知道要获取的列时,这是有效的(这不会改变)。

如果你需要动态地决定列,这是行不通的。

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

public static final String FIND_PROJECTS = "select ac_year_id,ac_year from tbl_au_academic_year where ac_year_id=?1";

    @Query(value = FIND_PROJECTS, nativeQuery = true)
    public  List<Object[]> findByAcYearId(Integer ac_year_id);

这对我很有用

你可以在Repository类的@Query注释中设置nativeQuery = true,如下所示:

public static final String FIND_PROJECTS = "SELECT projectId, projectName FROM projects";

@Query(value = FIND_PROJECTS, nativeQuery = true)
public List<Object[]> findProjects();

请注意,您必须自己进行映射。使用常规的映射查找可能会更简单,除非你真的只需要这两个值:

public List<Project> findAll()

Spring数据文档可能也值得一看。

在我的情况下,我只需要json结果,这对我来说是有效的:

public interface SchoolRepository extends JpaRepository<School,Integer> {
    @Query("select s.id, s.name from School s")
    List<Object> getSchoolIdAndName();
}

控制器:

@Autowired
private SchoolRepository schoolRepository;

@ResponseBody
@RequestMapping("getschoolidandname.do")
public List<Object> getSchool() {
    List<Object> schools = schoolRepository.getSchoolIdAndName();
    return schools;
}