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

例如: SELECT projectName FROM projects


当前回答

Use:

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

其他回答

你可以使用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();

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

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

你可以更新你的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
}

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

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