我使用Spring JPA执行所有数据库操作。但是,我不知道如何从Spring JPA的表中选择特定的列?
例如: SELECT projectName FROM projects
我使用Spring JPA执行所有数据库操作。但是,我不知道如何从Spring JPA的表中选择特定的列?
例如: SELECT projectName FROM projects
当前回答
您可以在存储库接口类中应用下面的代码。
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);
其他回答
我不喜欢语法特别(它看起来有点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 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%有效的。 谢谢。
你可以使用@jombie给出的答案,并且:
将接口放在实体类之外的单独文件中; 是否使用本机查询(选择取决于您的需要); 不要为此重写findAll()方法,而是使用自己选择的名称; 记得用你的新接口返回一个参数化的List(例如List<SmallProject>)。