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

例如: SELECT projectName FROM projects


当前回答

使用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%有效的。 谢谢。

其他回答

您可以使用来自Spring Data JPA(文档)的投影。在你的例子中,创建接口:

interface ProjectIdAndName{
    String getId();
    String getName();
}

并将以下方法添加到存储库中

List<ProjectIdAndName> findAll();

你可以使用JPQL:

TypedQuery <Object[]> query = em.createQuery(
  "SELECT p.projectId, p.projectName FROM projects AS p", Object[].class);

List<Object[]> results = query.getResultList();

或者您可以使用本地SQL查询。

Query query = em.createNativeQuery("sql statement");
List<Object[]> results = 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);

Use:

@Query("SELECT e FROM #{#entityName} e where e.userId=:uid")
List<ClienteEnderecoEntity> findInfoByUid(@Param("uid") UUID uid);
{
   "Comments":"Why not using JDBCTemplate",
   "Url":"https://www.baeldung.com/spring-jdbc-jdbctemplate"
}