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

例如: SELECT projectName FROM projects


当前回答

你可以使用@jombie给出的答案,并且:

将接口放在实体类之外的单独文件中; 是否使用本机查询(选择取决于您的需要); 不要为此重写findAll()方法,而是使用自己选择的名称; 记得用你的新接口返回一个参数化的List(例如List<SmallProject>)。

其他回答

使用本机查询:

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

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

使用Spring Data JPA有一个从数据库中选择特定列的规定

----在DAOImpl ----

@Override
    @Transactional
    public List<Employee> getAllEmployee() throws Exception {
    LOGGER.info("Inside getAllEmployee");
    List<Employee> empList = empRepo.getNameAndCityOnly();
    return empList;
    }

----在回购----

public interface EmployeeRepository extends CrudRepository<Employee,Integer> {
    @Query("select e.name, e.city from Employee e" )
    List<Employee> getNameAndCityOnly();
}

这对我来说是100%有效的。 谢谢。

在本地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);

您可以在存储库接口类中应用下面的代码。

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);