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

例如: SELECT projectName FROM projects


当前回答

你可以更新你的JPARepository,如下所示。

@Query("select u.status from UserLogin u where u.userId = ?1 or u.email = ?1 or u.mobile = ?1")
public UserStatus findByUserIdOrEmailOrMobile(String loginId);

UserStatus为Enum

public enum UserStatus
{
    New,
    Active,
    Deactived,
    Suspended,
    Locked
}

其他回答

Use:

@Query("SELECT e FROM #{#entityName} e where e.userId=:uid")
List<ClienteEnderecoEntity> findInfoByUid(@Param("uid") UUID uid);

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

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

在我的情况下,我只需要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;
}

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