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

例如: SELECT projectName FROM projects


当前回答

{
   "Comments":"Why not using JDBCTemplate",
   "Url":"https://www.baeldung.com/spring-jdbc-jdbctemplate"
}

其他回答

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

你可以在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数据文档可能也值得一看。

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

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

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

List<ProjectIdAndName> findAll();
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);

这对我很有用

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

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